Debian Codegraph @

src/util/log.c

raw
1 /*
2 * Log Context
3 *
4 * The log context provides an infrastructure to send log-messages to the
5 * system log daemon. Both structured and unstructured logging is supported.
6 * Depending on which logging daemon is used, a compatible mode is selected.
7 *
8 * Right now, these modes are supported:
9 *
10 * * stderr: Stream-based, unstructured logging to the inherited stderr
11 * channel.
12 * This is the default.
13 *
14 * * journal: Datagram-based, structured logging to the journal. Other
15 * journal-API-compatible daemons can be used as well. No
16 * journal-specific API besides the datagram socket is used.
17 *
18 * The logging API provides a staging buffer to assemble structured log
19 * messages. Once a message is complete, it must be committed, which will send
20 * it out and prepare the context for the next message.
21 *
22 * The log_*append*() APIs append log fields to the staging buffer. They can
23 * be used consecutively. Convenience wrappers are provided to add the most
24 * common structured fields. The staging buffer should only be used for
25 * structured logging. The main log-message is not part of it.
26 *
27 * Once a log message is completed, the log_*commit*() APIs commit the log
28 * message. At the time of commit, the caller must provide the actual main log
29 * message, which appears in the logs. Multiple convenience wrappers are
30 * provided to allow formatted messages.
31 * Note that depending on the backend, the structured fields might be
32 * discarded. Not all logging systems support them.
33 *
34 * By default, logging is synchronous and blocking. That is, no data is
35 * buffered in the log-context once a message is committed. All data is written
36 * into the socket in a blocking manner. The data will be buffered in the
37 * kernel socket queues, of course.
38 * This mode is not always desirable. In particular, we allow logging on behalf
39 * of peers in dbus-broker. This means, whenever a peer screws up, we often
40 * have more information than the peer itself, so we want to log data on behalf
41 * of them. This, however, makes us susceptible to DoS attacks. Hence, we
42 * support a lossy mode. If a log context is set to lossy mode, messages will
43 * be submitted to the socket in non-blocking mode. Once the kernel buffers run
44 * full, we submit a single, one-time, synchronous warning to the log, and from
45 * then on will discard log messages, if the kernel buffers are full.
46 *
47 * Lastly, please note that each log context must not be used from multiple
48 * threads. Use separate contexts for each thread. Also be aware that stream
49 * sockets do not have atomic writes, so you might need separate sockets.
50 *
51 * In case of structured logging, we support:
52 *
53 * * MESSAGE: The string-formatted log message.
54 *
55 * * CODE_FILE: Source-code file where the logging call originated. Usually
56 * corresponds to the expanded __FILE__ constant.
57 *
58 * * CODE_LINE: Source-code line number where the logging call originated.
59 * Usually corresponds to the expanded __LINE__ constant.
60 *
61 * * CODE_FUNC: Source-code function where the logging call originated.
62 * Usually correspoends to the expanded __func__ constant.
63 *
64 * * PRIORITY: Syslog-compatible log priority formatted as integer. See
65 * syslog.h for details on LOG_EMERG..LOG_DEBUG.
66 *
67 * * SYSLOG_FACILITY: Syslog facility formatted as integer.
68 *
69 * * SYSLOG_IDENTIFIER: Name of the program where the log message
70 * originated.
71 *
72 * * ERRNO: Errno-style error code that caused the log-message (or 0 if
73 * none).
74 *
75 * * DBUS_BROKER_LOG_DROPPED: Number of total log messages that were
76 * dropped so far due to excessive logging.
77 */
78
79 #include <c-stdaux.h>
80 #include <linux/sockios.h>
81 #include <stdlib.h>
82 #include <sys/ioctl.h>
83 #include <sys/mman.h>
84 #include <sys/socket.h>
85 #include <sys/syslog.h>
86 #include "util/error.h"
87 #include "util/log.h"
88 #include "util/misc.h"
89
90 /* lets retrict log records to 2MiB */
91 #define LOG_SIZE_MAX (2ULL * 1024ULL * 1024ULL)
92
93 /* warning that is sent on first dropped log message */
94 #define LOG_WARNING_DROPPED "<3>Log messages dropped\n"
95
96 /**
97 * log_init() - initialize log context
98 * @log: log context to initialize
99 *
100 * This initializes the log-context @log with no output configured. Hence, all
101 * log messages will be silently dropped.
102 */
103 void log_init(Log *log) {
104 *log = (Log)LOG_NULL;
105 log->mode = LOG_MODE_NONE;
106 log->consumed = false;
107 log->map_size = LOG_SIZE_MAX;
108 /* NOTE: Other log_init_*() variants override these. */
109 }
110
111 /**
112 * log_init_stderr() - initialize log context
113 * @log: log context to initialize
114 * @stderr_fd: stderr stream FD to use
115 *
116 * This initializes the log-context @log and prepares it for output to stderr
117 * given its file-descriptor as @stderr_fd. Note that the file-descriptor is
118 * not consumed, but ownership is retained by the caller.
119 */
120 void log_init_stderr(Log *log, int stderr_fd) {
121 c_assert(stderr_fd >= 0);
122
123 log_init(log);
124 log->log_fd = stderr_fd;
125 log->mode = LOG_MODE_STDERR;
126 log->consumed = false;
127 }
128
129 /**
130 * log_init_journal() - initialize log context
131 * @log: log context to initialize
132 * @journal_fd: Datagram-FD to the journal
133 *
134 * This initializes the log-context @log with the journal datagram
135 * socket @journal_fd to be used for log-messages.
136 */
137 void log_init_journal(Log *log, int journal_fd) {
138 c_assert(journal_fd >= 0);
139
140 log_init(log);
141 log->log_fd = journal_fd;
142 log->mode = LOG_MODE_JOURNAL;
143 log->consumed = false;
144 }
145
146 /**
147 * log_init_journal_consume() - initialize log context
148 * @log: log context to initialize
149 * @journal_fd: Datagram-FD to the journal
150 *
151 * This initializes the log-context @log and consumes the journal datagram
152 * socket @journal_fd to be used for log-messages.
153 */
154 void log_init_journal_consume(Log *log, int journal_fd) {
155 c_assert(journal_fd >= 0);
156
157 log_init(log);
158 log->log_fd = journal_fd;
159 log->mode = LOG_MODE_JOURNAL;
160 log->consumed = true;
161 }
162
163 /**
164 * log_deinit() - deinitialize log context
165 * @log: log to operate on
166 *
167 * This deinitializes the log context @log and releases all resources. The
168 * context is reset to LOG_NULL afterwards.
169 *
170 * Calling this on LOG_NULL is a no-op.
171 */
172 void log_deinit(Log *log) {
173 if (log->map != MAP_FAILED)
174 munmap(log->map, log->map_size);
175 c_close(log->mem_fd);
176 if (log->consumed)
177 c_close(log->log_fd);
178 *log = (Log)LOG_NULL;
179 }
180
181 /**
182 * log_get_fd() - get logging fd
183 * @log: log context to operate on
184 *
185 * This returns the file-descriptor used to submit log messages to. This is
186 * usually the same FD that was passed to the constructor. Note that the FD is
187 * still owned by the log context, so it must be treated as read-only.
188 *
189 * Return: Log file-descriptor in use, or -1 if none.
190 */
191 int log_get_fd(Log *log) {
192 return log->log_fd;
193 }
194
195 /**
196 * log_set_lossy() - set lossy mode
197 * @log: log context to operate on
198 * @lossy: lossy mode to set
199 *
200 * This changes the lossy-mode of the log context @log. If @lossy is false, all
201 * log messages will be sent in blocking mode to the logging daemon, and
202 * transmission will be reliable.
203 *
204 * If @lossy is true, logging will be lossy. This means, any message submitted
205 * to the log context might be dropped, with the advantage of logging being
206 * safe even in quotad contexts.
207 *
208 * Default is non-lossy mode.
209 */
210 void log_set_lossy(Log *log, bool lossy) {
211 log->lossy = lossy;
212 }
213
214 static bool log_alloc(Log *log) {
215 _c_cleanup_(c_closep) int mem_fd = -1;
216 void *p;
217 int r;
218
219 if (log->error)
220 return false;
221 if (log->map != MAP_FAILED)
222 return true;
223
224 c_assert(!log->offset);
225
226 /*
227 * systemd-journald used to verify seals explicitly, and any new seal
228 * showing up was refused. Hence, we cannot set MFD_NOEXEC but have to
229 * use MFD_EXEC.
230 */
231 mem_fd = misc_memfd(
232 "dbus-broker-log",
233 MISC_MFD_CLOEXEC | MISC_MFD_ALLOW_SEALING | MISC_MFD_EXEC,
234 0
235 );
236 if (mem_fd < 0) {
237 /*
238 * In case of EINVAL, memfd_create() is not available. We then
239 * use normal anonymous memory as backing.
240 */
241 if (mem_fd != -EINVAL) {
242 log->error = error_fold(mem_fd);
243 return false;
244 }
245 mem_fd = -1;
246
247 p = mmap(NULL, log->map_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
248 if (p == MAP_FAILED) {
249 log->error = error_origin(-errno);
250 return false;
251 }
252 } else {
253 r = ftruncate(mem_fd, log->map_size);
254 if (r < 0) {
255 log->error = error_origin(-errno);
256 return false;
257 }
258
259 p = mmap(NULL, log->map_size, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd, 0);
260 if (p == MAP_FAILED) {
261 log->error = error_origin(-errno);
262 return false;
263 }
264 }
265
266 log->mem_fd = mem_fd;
267 log->map = p;
268 mem_fd = -1;
269 return true;
270 }
271
272 static int log_fd_send(int destination_fd, int payload_fd) {
273 union {
274 char buffer[CMSG_SPACE(sizeof(int))];
275 struct cmsghdr cmsg;
276 } control;
277 struct msghdr msg;
278 ssize_t l;
279
280 control.cmsg.cmsg_len = CMSG_LEN(sizeof(int));
281 control.cmsg.cmsg_level = SOL_SOCKET;
282 control.cmsg.cmsg_type = SCM_RIGHTS;
283 c_memcpy(CMSG_DATA(&control.cmsg), &payload_fd, sizeof(int));
284
285 msg = (struct msghdr){
286 .msg_control = &control.cmsg,
287 .msg_controllen = control.cmsg.cmsg_len,
288 };
289
290 l = sendmsg(destination_fd, &msg, MSG_NOSIGNAL);
291 if (l)
292 return (l < 0) ? error_origin(-errno) : error_origin(-ENOTRECOVERABLE);
293
294 return 0;
295 }
296
297 static int log_loop_send(int destination_fd, const void *blob, size_t n_blob) {
298 ssize_t l;
299
300 while (n_blob > 0) {
301 l = send(destination_fd, blob, n_blob, MSG_NOSIGNAL);
302 if (l < 0)
303 return error_origin(-errno);
304 else if (l == 0 || l > (ssize_t)n_blob)
305 return error_origin(-ENOTRECOVERABLE);
306
307 blob += l;
308 n_blob -= l;
309 }
310
311 return 0;
312 }
313
314 static int log_stream_send(Log *log) {
315 bool log_warn = false;
316 const void *blob = log->map;
317 size_t n_blob = log->offset;
318 ssize_t l;
319 int r, v;
320
321 /*
322 * Stream sockets are a bit nasty since they lack atomic writes. Hence,
323 * whenever we end up with a short-write in lossy mode, we need to
324 * finish the current message in synchronous mode, and then log a
325 * warning. Otherwise, we end up with a garbled output.
326 *
327 * Now, we remember whenever we dropped message. From then on, we only
328 * ever write messages if the output buffer of our socket is empty.
329 * Preferably, we would check that the message fits into the kernel
330 * buffer, but there is no way to do that. Hence, we simply require the
331 * buffer to be empty.
332 * This guarantees the operation will be non-blocking, as long as
333 * suitably sized log messages are used.
334 */
335
336 if (log->lossy) {
337 if (log->n_dropped) {
338 r = ioctl(log->log_fd, SIOCOUTQ, &v);
339 if (r < 0) {
340 return error_origin(-errno);
341 } else if (v) {
342 ++log->n_dropped;
343 return 0;
344 }
345 }
346
347 l = send(log->log_fd, blob, n_blob, MSG_NOSIGNAL | MSG_DONTWAIT);
348 if (l >= (ssize_t)n_blob) {
349 return 0;
350 } else if (l < 0) {
351 if (errno != EAGAIN)
352 return error_origin(-errno);
353
354 l = 0;
355 }
356
357 blob += l;
358 n_blob -= l;
359
360 if (!log->n_dropped++)
361 log_warn = true;
362 }
363
364 r = log_loop_send(log->log_fd, blob, n_blob);
365 if (r)
366 return error_trace(r);
367
368 if (log_warn) {
369 r = log_loop_send(log->log_fd,
370 LOG_WARNING_DROPPED,
371 strlen(LOG_WARNING_DROPPED));
372 if (r)
373 return error_trace(r);
374 }
375
376 return 0;
377 }
378
379 static int log_journal_send(Log *log) {
380 _c_cleanup_(c_closep) int mfd = -1;
381 ssize_t l;
382 int r;
383
384 l = send(log->log_fd,
385 log->map,
386 log->offset,
387 log->lossy ?
388 MSG_NOSIGNAL | MSG_DONTWAIT :
389 MSG_NOSIGNAL);
390 if (l == (ssize_t)log->offset) {
391 return 0;
392 } else if (l >= 0) {
393 /*
394 * Partially sent? This should not happen. We require datagram
395 * sockets that send atomically and never truncate unasked.
396 * Tell our caller about this, so they can deal with it.
397 */
398 return LOG_E_TRUNCATED;
399 } else if (errno == EAGAIN) {
400 goto out_drop;
401 } else if (errno != EMSGSIZE) {
402 return error_origin(-errno);
403 }
404
405 /*
406 * We could not send the message as a single datagram. Instead, we now
407 * seal the memfd and send it as payload of an empty datagram. The
408 * journal can deal with this and treats the memfd content as log
409 * message.
410 *
411 * Note that this means there is an inflight memfd pending on the
412 * journal that is accounted on us as long as the journal did not read
413 * it, yet. Hence, clients should never be able to trigger such log
414 * messages, otherwise they could exploit this and make us exceed our
415 * inflight FD limit.
416 *
417 * We could send a pipe-fd as barrier and block on it. Hence, we would
418 * be able to know at which point our messages are no longer inflight.
419 * However, this would be a quite expensive code-path, making this
420 * entire path completely useless.
421 *
422 * Long story short: Do not write excessive log messages, unless
423 * debugging is enabled in some way.
424 */
425
426 if (log->lossy || log->mem_fd < 0)
427 goto out_drop;
428
429 mfd = log->mem_fd;
430 log->mem_fd = -1;
431 munmap(log->map, log->map_size);
432 log->map = MAP_FAILED;
433
434 r = ftruncate(mfd, log->offset);
435 if (r < 0)
436 return error_origin(-errno);
437
438 r = misc_memfd_add_seals(
439 mfd,
440 MISC_F_SEAL_SEAL | MISC_F_SEAL_SHRINK |
441 MISC_F_SEAL_GROW | MISC_F_SEAL_WRITE
442 );
443 if (r < 0)
444 return error_origin(-errno);
445
446 r = log_fd_send(log->log_fd, mfd);
447 if (r < 0)
448 return error_trace(r);
449
450 return 0;
451
452 out_drop:
453 if (!log->n_dropped++) {
454 l = send(log->log_fd,
455 LOG_WARNING_DROPPED,
456 strlen(LOG_WARNING_DROPPED),
457 MSG_NOSIGNAL);
458 if (l < 0)
459 return error_origin(-errno);
460 }
461
462 return 0;
463 }
464
465 static int log_commit_stderr(Log *log, const char *format, va_list args) {
466 int r;
467
468 /*
469 * Lets format the log-message in our staging buffer and print it out.
470 * Note that we don't support structured logging. Hence, we simply
471 * ignore anything that is in the staging buffer and instead just print
472 * our message.
473 * Sadly, `%r' is still no standardized format specifier, so we need
474 * the separate calls into log_append() here.
475 */
476
477 log->offset = 0;
478
479 if (format && *format) {
480 log_appendf(log, "<%d>", log->level ?: LOG_INFO);
481 log_vappendf(log, format, args);
482 log_appends(log, "\n");
483 }
484
485 if (log->error)
486 r = error_trace(log->error);
487 else if (log->offset)
488 r = log_stream_send(log);
489 else
490 r = 0;
491
492 return error_trace(r);
493 }
494
495 static int log_commit_journal(Log *log, const char *format, va_list args) {
496 int r;
497
498 /*
499 * Lets append `MESSAGE=%s\n' to the staging buffer and then submit the
500 * entire blob to the journal. We support passing it as sealed memfd in
501 * case it exceeds the datagram maximum.
502 * Sadly, `%r' is still no standardized format specifier, so we need
503 * the separate calls into log_append() here.
504 */
505
506 if (format && *format) {
507 log_appends(log, "MESSAGE=");
508 log_vappendf(log, format, args);
509 log_appends(log, "\n");
510 }
511
512 if (log->error)
513 r = error_trace(log->error);
514 else if (log->offset)
515 r = log_journal_send(log);
516 else
517 r = 0;
518
519 return error_trace(r);
520 }
521
522 /**
523 * log_vcommitf() - commit log message
524 * @log: log to operate on
525 * @format: log message format string
526 * @args: arguments for format string
527 *
528 * This formats a log message and commits it. @format is used as format string
529 * for the log message, with @args filled in at the respective places.
530 *
531 * Any previously appended log fields are amended to the log message and
532 * submitted with it. In case the log output does not support structured
533 * logging, they will be lost, and only the message itself is submitted.
534 *
535 * If the pending log message is poisoned, or if it could not be submitted,
536 * an error will be returned. After this call returns (regardless whether it
537 * failed or not), the log context is ready to take the next log message.
538 *
539 * Return: 0 on success, LOG_E_TRUNCATED if the message was truncated by the
540 * log channel, LOG_E_OVERSIZED if the message exceeded the maximum
541 * size, and negative error code on failure.
542 */
543 int log_vcommitf(Log *log, const char *format, va_list args) {
544 int r;
545
546 switch (log->mode) {
547 case LOG_MODE_NONE:
548 r = error_trace(log->error);
549 break;
550 case LOG_MODE_STDERR:
551 r = log_commit_stderr(log, format, args);
552 break;
553 case LOG_MODE_JOURNAL:
554 r = log_commit_journal(log, format, args);
555 break;
556 default:
557 r = error_origin(-ENOTRECOVERABLE);
558 break;
559 }
560
561 log->error = 0;
562 log->level = 0;
563 log->offset = 0;
564
565 return r;
566 }
567
568 /**
569 * log_append() - append structured fields
570 * @log: log context to operate on
571 * @data: data to append
572 * @n_data: length of data to append
573 *
574 * This appends the given data to the structured log staging buffer. Note that
575 * you can encode binary data, as long as you follow the protocol of journald.
576 * But you're recommended to just insert newline separated ascii key-value
577 * pairs.
578 */
579 void log_append(Log *log, const void *data, size_t n_data) {
580 if (!n_data || !log_alloc(log))
581 return;
582
583 if (log->map_size - log->offset < n_data) {
584 log->error = LOG_E_TRUNCATED;
585 return;
586 }
587
588 c_memcpy(log->map + log->offset, data, n_data);
589 log->offset += n_data;
590 }
591
592 /**
593 * log_vappendf() - append structured fields
594 * @log: log context to operate on
595 * @format: formatted data to append
596 * @args: arguments to fill in via format string
597 *
598 * This is similar to log_append(), but uses printf-style formatting rather
599 * than copying a blob verbatim.
600 */
601 void log_vappendf(Log *log, const char *format, va_list args) {
602 int r;
603
604 if (!log_alloc(log))
605 return;
606
607 r = vsnprintf(log->map + log->offset,
608 log->map_size - log->offset,
609 format,
610 args);
611 if (r < 0 || r >= (ssize_t)(log->map_size - log->offset)) {
612 log->error = LOG_E_TRUNCATED;
613 return;
614 }
615
616 log->offset += r;
617 }
618
619 /**
620 * log_append_common() - append common log entries
621 * @log: log to operate on
622 * @level: syslog level indicator
623 * @error: errno-style error code
624 * @id: log message ID, or NULL
625 * @file: source file
626 * @line: source line
627 * @func: source function
628 *
629 * This appends known, common fields to the current log message. This should be
630 * called for every log message.
631 */
632 void log_append_common(Log *log,
633 int level,
634 int error,
635 const char *id,
636 const char *file,
637 int line,
638 const char *func) {
639 /*
640 * Use LOG_DAEMON if the log-facility is 0. Most people don't specify
641 * any facility, so lets just apply a default. Note that 0 actually
642 * means 'kernel' as facility, but we just treat it as unspecified
643 * here, since no-one should specify 'kernel' from user-space.
644 */
645 level = LOG_MAKEPRI(LOG_FAC(level) ?: LOG_DAEMON,
646 LOG_PRI(level) ?: LOG_INFO);
647
648 /*
649 * Always remember the level of the current log message. In case the
650 * journal is not used, we can still prefix the syslog / stderr
651 * messages with it.
652 */
653 log->level = level;
654
655 /*
656 * If we have a journal-entry (or successfully allocated one), simply
657 * append the known, common fields.
658 */
659 if (log_alloc(log)) {
660 log_appendf(log,
661 "PRIORITY=%i\n"
662 "SYSLOG_FACILITY=%i\n"
663 "SYSLOG_IDENTIFIER=%s\n"
664 "ERRNO=%i\n"
665 "CODE_FILE=%s\n"
666 "CODE_LINE=%i\n"
667 "CODE_FUNC=%s\n"
668 "DBUS_BROKER_LOG_DROPPED=%"PRIu64"\n",
669 LOG_PRI(level),
670 LOG_FAC(level),
671 program_invocation_short_name,
672 error,
673 file,
674 line,
675 func,
676 log->n_dropped);
677 if (id)
678 log_appendf(log, "MESSAGE_ID=%s\n", id);
679 }
680 }