chiark / gitweb /
basic/log: use getenv instead of secure_getenv
[elogind.git] / src / basic / log.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdarg.h>
25 #include <stddef.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/signalfd.h>
29 #include <sys/socket.h>
30 #include <sys/time.h>
31 #include <sys/uio.h>
32 #include <sys/un.h>
33 #include <time.h>
34 #include <unistd.h>
35
36 #include "sd-messages.h"
37
38 #include "alloc-util.h"
39 #include "fd-util.h"
40 #include "format-util.h"
41 #include "io-util.h"
42 #include "log.h"
43 #include "macro.h"
44 #include "missing.h"
45 #include "parse-util.h"
46 #include "proc-cmdline.h"
47 #include "process-util.h"
48 #include "signal-util.h"
49 #include "socket-util.h"
50 #include "stdio-util.h"
51 #include "string-table.h"
52 #include "string-util.h"
53 #include "syslog-util.h"
54 #include "terminal-util.h"
55 #include "time-util.h"
56 #include "util.h"
57
58 #define SNDBUF_SIZE (8*1024*1024)
59
60 static LogTarget log_target = LOG_TARGET_CONSOLE;
61 static int log_max_level[] = {LOG_INFO, LOG_INFO};
62 assert_cc(ELEMENTSOF(log_max_level) == _LOG_REALM_MAX);
63 static int log_facility = LOG_DAEMON;
64
65 static int console_fd = STDERR_FILENO;
66 static int syslog_fd = -1;
67 static int kmsg_fd = -1;
68 static int journal_fd = -1;
69
70 static bool syslog_is_stream = false;
71
72 static bool show_color = false;
73 static bool show_location = false;
74
75 #if 0 /// UNNEEDED by elogind
76 static bool upgrade_syslog_to_journal = false;
77 #endif // 0
78 static bool always_reopen_console = false;
79
80 /* Akin to glibc's __abort_msg; which is private and we hence cannot
81  * use here. */
82 static char *log_abort_msg = NULL;
83
84 void log_close_console(void) {
85
86         if (console_fd < 0)
87                 return;
88
89         if (getpid() == 1) {
90                 if (console_fd >= 3)
91                         safe_close(console_fd);
92
93                 console_fd = -1;
94         }
95 }
96
97 static int log_open_console(void) {
98
99         if (console_fd >= 0)
100                 return 0;
101
102         if (always_reopen_console) {
103                 console_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
104                 if (console_fd < 0)
105                         return console_fd;
106         } else
107                 console_fd = STDERR_FILENO;
108
109         return 0;
110 }
111
112 void log_close_kmsg(void) {
113         kmsg_fd = safe_close(kmsg_fd);
114 }
115
116 static int log_open_kmsg(void) {
117
118         if (kmsg_fd >= 0)
119                 return 0;
120
121         kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
122         if (kmsg_fd < 0)
123                 return -errno;
124
125         return 0;
126 }
127
128 void log_close_syslog(void) {
129         syslog_fd = safe_close(syslog_fd);
130 }
131
132 static int create_log_socket(int type) {
133         struct timeval tv;
134         int fd;
135
136         fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
137         if (fd < 0)
138                 return -errno;
139
140         (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
141
142         /* We need a blocking fd here since we'd otherwise lose
143         messages way too early. However, let's not hang forever in the
144         unlikely case of a deadlock. */
145         if (getpid() == 1)
146                 timeval_store(&tv, 10 * USEC_PER_MSEC);
147         else
148                 timeval_store(&tv, 10 * USEC_PER_SEC);
149         (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
150
151         return fd;
152 }
153
154 static int log_open_syslog(void) {
155
156         static const union sockaddr_union sa = {
157                 .un.sun_family = AF_UNIX,
158                 .un.sun_path = "/dev/log",
159         };
160
161         int r;
162
163         if (syslog_fd >= 0)
164                 return 0;
165
166         syslog_fd = create_log_socket(SOCK_DGRAM);
167         if (syslog_fd < 0) {
168                 r = syslog_fd;
169                 goto fail;
170         }
171
172         if (connect(syslog_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
173                 safe_close(syslog_fd);
174
175                 /* Some legacy syslog systems still use stream
176                  * sockets. They really shouldn't. But what can we
177                  * do... */
178                 syslog_fd = create_log_socket(SOCK_STREAM);
179                 if (syslog_fd < 0) {
180                         r = syslog_fd;
181                         goto fail;
182                 }
183
184                 if (connect(syslog_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
185                         r = -errno;
186                         goto fail;
187                 }
188
189                 syslog_is_stream = true;
190         } else
191                 syslog_is_stream = false;
192
193         return 0;
194
195 fail:
196         log_close_syslog();
197         return r;
198 }
199
200 void log_close_journal(void) {
201 #if 0 /// elogind does not support journald
202         journal_fd = safe_close(journal_fd);
203 #endif // 0
204 }
205
206 #if 0 /// UNNEEDED by elogind
207 static int log_open_journal(void) {
208
209         static const union sockaddr_union sa = {
210                 .un.sun_family = AF_UNIX,
211                 .un.sun_path = "/run/systemd/journal/socket",
212         };
213
214         int r;
215
216         if (journal_fd >= 0)
217                 return 0;
218
219         journal_fd = create_log_socket(SOCK_DGRAM);
220         if (journal_fd < 0) {
221                 r = journal_fd;
222                 goto fail;
223         }
224
225         if (connect(journal_fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
226                 r = -errno;
227                 goto fail;
228         }
229
230         return 0;
231
232 fail:
233         log_close_journal();
234         return r;
235 }
236 #endif // 0
237
238 int log_open(void) {
239         int r;
240
241         /* If we don't use the console we close it here, to not get
242          * killed by SAK. If we don't use syslog we close it here so
243          * that we are not confused by somebody deleting the socket in
244          * the fs. If we don't use /dev/kmsg we still keep it open,
245          * because there is no reason to close it. */
246
247         if (log_target == LOG_TARGET_NULL) {
248                 log_close_journal();
249                 log_close_syslog();
250                 log_close_console();
251                 return 0;
252         }
253
254         if (!IN_SET(log_target, LOG_TARGET_AUTO, LOG_TARGET_SAFE) ||
255             getpid() == 1 ||
256             isatty(STDERR_FILENO) <= 0) {
257
258 #if 0 /// elogind does not support logging to systemd-journald
259                 if (IN_SET(log_target, LOG_TARGET_AUTO,
260                                        LOG_TARGET_JOURNAL_OR_KMSG,
261                                        LOG_TARGET_JOURNAL)) {
262                         r = log_open_journal();
263                         if (r >= 0) {
264                                 log_close_syslog();
265                                 log_close_console();
266                                 return r;
267                         }
268                 }
269 #endif // 0
270
271                 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
272                                        LOG_TARGET_SYSLOG)) {
273                         r = log_open_syslog();
274                         if (r >= 0) {
275                                 log_close_journal();
276                                 log_close_console();
277                                 return r;
278                         }
279                 }
280
281                 if (IN_SET(log_target, LOG_TARGET_AUTO,
282                                        LOG_TARGET_SAFE,
283                                        LOG_TARGET_JOURNAL_OR_KMSG,
284                                        LOG_TARGET_SYSLOG_OR_KMSG,
285                                        LOG_TARGET_KMSG)) {
286                         r = log_open_kmsg();
287                         if (r >= 0) {
288                                 log_close_journal();
289                                 log_close_syslog();
290                                 log_close_console();
291                                 return r;
292                         }
293                 }
294         }
295
296         log_close_journal();
297         log_close_syslog();
298
299         return log_open_console();
300 }
301
302 void log_set_target(LogTarget target) {
303         assert(target >= 0);
304         assert(target < _LOG_TARGET_MAX);
305
306 #if 0 /// elogind does not support logging to systemd-journald
307         if (upgrade_syslog_to_journal) {
308                 if (target == LOG_TARGET_SYSLOG)
309                         target = LOG_TARGET_JOURNAL;
310                 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
311                         target = LOG_TARGET_JOURNAL_OR_KMSG;
312         }
313 #endif // 0
314
315         log_target = target;
316 }
317
318 void log_close(void) {
319         log_close_journal();
320         log_close_syslog();
321         log_close_kmsg();
322         log_close_console();
323 }
324
325 #if 0 /// UNNEEDED by elogind
326 void log_forget_fds(void) {
327         console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
328 }
329 #endif // 0
330
331 void log_set_max_level_realm(LogRealm realm, int level) {
332         assert((level & LOG_PRIMASK) == level);
333         assert(realm < ELEMENTSOF(log_max_level));
334
335         log_max_level[realm] = level;
336 }
337
338 void log_set_facility(int facility) {
339         log_facility = facility;
340 }
341
342 static int write_to_console(
343                 int level,
344                 int error,
345                 const char *file,
346                 int line,
347                 const char *func,
348                 const char *buffer) {
349
350         char location[256], prefix[1 + DECIMAL_STR_MAX(int) + 2];
351         struct iovec iovec[6] = {};
352         unsigned n = 0;
353         bool highlight;
354
355         if (console_fd < 0)
356                 return 0;
357
358         if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
359                 xsprintf(prefix, "<%i>", level);
360                 IOVEC_SET_STRING(iovec[n++], prefix);
361         }
362
363         highlight = LOG_PRI(level) <= LOG_ERR && show_color;
364
365         if (show_location) {
366                 snprintf(location, sizeof(location), "(%s:%i) ", file, line);
367                 IOVEC_SET_STRING(iovec[n++], location);
368         }
369
370         if (highlight)
371                 IOVEC_SET_STRING(iovec[n++], ANSI_HIGHLIGHT_RED);
372         IOVEC_SET_STRING(iovec[n++], buffer);
373         if (highlight)
374                 IOVEC_SET_STRING(iovec[n++], ANSI_NORMAL);
375         IOVEC_SET_STRING(iovec[n++], "\n");
376
377         if (writev(console_fd, iovec, n) < 0) {
378
379                 if (errno == EIO && getpid() == 1) {
380
381                         /* If somebody tried to kick us from our
382                          * console tty (via vhangup() or suchlike),
383                          * try to reconnect */
384
385                         log_close_console();
386                         log_open_console();
387
388                         if (console_fd < 0)
389                                 return 0;
390
391                         if (writev(console_fd, iovec, n) < 0)
392                                 return -errno;
393                 } else
394                         return -errno;
395         }
396
397         return 1;
398 }
399
400 static int write_to_syslog(
401                 int level,
402                 int error,
403                 const char *file,
404                 int line,
405                 const char *func,
406                 const char *buffer) {
407
408         char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
409              header_time[64],
410              header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
411         struct iovec iovec[5] = {};
412         struct msghdr msghdr = {
413                 .msg_iov = iovec,
414                 .msg_iovlen = ELEMENTSOF(iovec),
415         };
416         time_t t;
417         struct tm *tm;
418
419         if (syslog_fd < 0)
420                 return 0;
421
422         xsprintf(header_priority, "<%i>", level);
423
424         t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
425         tm = localtime(&t);
426         if (!tm)
427                 return -EINVAL;
428
429         if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
430                 return -EINVAL;
431
432         xsprintf(header_pid, "["PID_FMT"]: ", getpid());
433
434         IOVEC_SET_STRING(iovec[0], header_priority);
435         IOVEC_SET_STRING(iovec[1], header_time);
436         IOVEC_SET_STRING(iovec[2], program_invocation_short_name);
437         IOVEC_SET_STRING(iovec[3], header_pid);
438         IOVEC_SET_STRING(iovec[4], buffer);
439
440         /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
441         if (syslog_is_stream)
442                 iovec[4].iov_len++;
443
444         for (;;) {
445                 ssize_t n;
446
447                 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
448                 if (n < 0)
449                         return -errno;
450
451                 if (!syslog_is_stream ||
452                     (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
453                         break;
454
455                 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
456         }
457
458         return 1;
459 }
460
461 static int write_to_kmsg(
462                 int level,
463                 int error,
464                 const char *file,
465                 int line,
466                 const char *func,
467                 const char *buffer) {
468
469         char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
470              header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
471         struct iovec iovec[5] = {};
472
473         if (kmsg_fd < 0)
474                 return 0;
475
476         xsprintf(header_priority, "<%i>", level);
477         xsprintf(header_pid, "["PID_FMT"]: ", getpid());
478
479         IOVEC_SET_STRING(iovec[0], header_priority);
480         IOVEC_SET_STRING(iovec[1], program_invocation_short_name);
481         IOVEC_SET_STRING(iovec[2], header_pid);
482         IOVEC_SET_STRING(iovec[3], buffer);
483         IOVEC_SET_STRING(iovec[4], "\n");
484
485         if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
486                 return -errno;
487
488         return 1;
489 }
490
491 #if 0 /// UNNEEDED by elogind
492 static int log_do_header(
493                 char *header,
494                 size_t size,
495                 int level,
496                 int error,
497                 const char *file, int line, const char *func,
498                 const char *object_field, const char *object,
499                 const char *extra_field, const char *extra) {
500
501         snprintf(header, size,
502                  "PRIORITY=%i\n"
503                  "SYSLOG_FACILITY=%i\n"
504                  "%s%s%s"
505                  "%s%.*i%s"
506                  "%s%s%s"
507                  "%s%.*i%s"
508                  "%s%s%s"
509                  "%s%s%s"
510                  "SYSLOG_IDENTIFIER=%s\n",
511                  LOG_PRI(level),
512                  LOG_FAC(level),
513                  isempty(file) ? "" : "CODE_FILE=",
514                  isempty(file) ? "" : file,
515                  isempty(file) ? "" : "\n",
516                  line ? "CODE_LINE=" : "",
517                  line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
518                  line ? "\n" : "",
519                  isempty(func) ? "" : "CODE_FUNC=",
520                  isempty(func) ? "" : func,
521                  isempty(func) ? "" : "\n",
522                  error ? "ERRNO=" : "",
523                  error ? 1 : 0, error,
524                  error ? "\n" : "",
525                  isempty(object) ? "" : object_field,
526                  isempty(object) ? "" : object,
527                  isempty(object) ? "" : "\n",
528                  isempty(extra) ? "" : extra_field,
529                  isempty(extra) ? "" : extra,
530                  isempty(extra) ? "" : "\n",
531                  program_invocation_short_name);
532
533         return 0;
534 }
535
536 static int write_to_journal(
537                 int level,
538                 int error,
539                 const char *file,
540                 int line,
541                 const char *func,
542                 const char *object_field,
543                 const char *object,
544                 const char *extra_field,
545                 const char *extra,
546                 const char *buffer) {
547
548         char header[LINE_MAX];
549         struct iovec iovec[4] = {};
550         struct msghdr mh = {};
551
552         if (journal_fd < 0)
553                 return 0;
554
555         log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
556
557         IOVEC_SET_STRING(iovec[0], header);
558         IOVEC_SET_STRING(iovec[1], "MESSAGE=");
559         IOVEC_SET_STRING(iovec[2], buffer);
560         IOVEC_SET_STRING(iovec[3], "\n");
561
562         mh.msg_iov = iovec;
563         mh.msg_iovlen = ELEMENTSOF(iovec);
564
565         if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
566                 return -errno;
567
568         return 1;
569 }
570 #endif // 0
571
572 int log_dispatch_internal(
573                 int level,
574                 int error,
575                 const char *file,
576                 int line,
577                 const char *func,
578                 const char *object_field,
579                 const char *object,
580                 const char *extra,
581                 const char *extra_field,
582                 char *buffer) {
583
584         assert(buffer);
585
586         if (error < 0)
587                 error = -error;
588
589         if (log_target == LOG_TARGET_NULL)
590                 return -error;
591
592         /* Patch in LOG_DAEMON facility if necessary */
593         if ((level & LOG_FACMASK) == 0)
594                 level = log_facility | LOG_PRI(level);
595
596         do {
597                 char *e;
598                 int k = 0;
599
600                 buffer += strspn(buffer, NEWLINE);
601
602                 if (buffer[0] == 0)
603                         break;
604
605                 if ((e = strpbrk(buffer, NEWLINE)))
606                         *(e++) = 0;
607
608 #if 0 /// elogind does not support logging to systemd-journald
609                 if (IN_SET(log_target, LOG_TARGET_AUTO,
610                                        LOG_TARGET_JOURNAL_OR_KMSG,
611                                        LOG_TARGET_JOURNAL)) {
612
613                         k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
614                         if (k < 0) {
615                                 if (k != -EAGAIN)
616                                         log_close_journal();
617                                 log_open_kmsg();
618                         }
619                 }
620 #endif // 0
621
622                 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
623                                        LOG_TARGET_SYSLOG)) {
624
625                         k = write_to_syslog(level, error, file, line, func, buffer);
626                         if (k < 0) {
627                                 if (k != -EAGAIN)
628                                         log_close_syslog();
629                                 log_open_kmsg();
630                         }
631                 }
632
633                 if (k <= 0 &&
634                     IN_SET(log_target, LOG_TARGET_AUTO,
635                                        LOG_TARGET_SAFE,
636                                        LOG_TARGET_SYSLOG_OR_KMSG,
637                                        LOG_TARGET_JOURNAL_OR_KMSG,
638                                        LOG_TARGET_KMSG)) {
639
640                         k = write_to_kmsg(level, error, file, line, func, buffer);
641                         if (k < 0) {
642                                 log_close_kmsg();
643                                 log_open_console();
644                         }
645                 }
646
647                 if (k <= 0)
648                         (void) write_to_console(level, error, file, line, func, buffer);
649
650                 buffer = e;
651         } while (buffer);
652
653         return -error;
654 }
655
656 int log_dump_internal(
657                 int level,
658                 int error,
659                 const char *file,
660                 int line,
661                 const char *func,
662                 char *buffer) {
663
664         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
665         PROTECT_ERRNO;
666
667         /* This modifies the buffer... */
668
669         if (error < 0)
670                 error = -error;
671
672         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
673                 return -error;
674
675         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
676 }
677
678 int log_internalv_realm(
679                 int level,
680                 int error,
681                 const char *file,
682                 int line,
683                 const char *func,
684                 const char *format,
685                 va_list ap) {
686
687         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
688         char buffer[LINE_MAX];
689         PROTECT_ERRNO;
690
691         if (error < 0)
692                 error = -error;
693
694         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
695                 return -error;
696
697         /* Make sure that %m maps to the specified error */
698         if (error != 0)
699                 errno = error;
700
701         vsnprintf(buffer, sizeof(buffer), format, ap);
702
703         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
704 }
705
706 int log_internal_realm(
707                 int level,
708                 int error,
709                 const char *file,
710                 int line,
711                 const char *func,
712                 const char *format, ...) {
713
714         va_list ap;
715         int r;
716
717         va_start(ap, format);
718         r = log_internalv_realm(level, error, file, line, func, format, ap);
719         va_end(ap);
720
721         return r;
722 }
723
724 int log_object_internalv(
725                 int level,
726                 int error,
727                 const char *file,
728                 int line,
729                 const char *func,
730                 const char *object_field,
731                 const char *object,
732                 const char *extra_field,
733                 const char *extra,
734                 const char *format,
735                 va_list ap) {
736
737         PROTECT_ERRNO;
738         char *buffer, *b;
739
740         if (error < 0)
741                 error = -error;
742
743         if (_likely_(LOG_PRI(level) > log_max_level[LOG_REALM_SYSTEMD]))
744                 return -error;
745
746         /* Make sure that %m maps to the specified error */
747         if (error != 0)
748                 errno = error;
749
750         /* Prepend the object name before the message */
751         if (object) {
752                 size_t n;
753
754                 n = strlen(object);
755                 buffer = newa(char, n + 2 + LINE_MAX);
756                 b = stpcpy(stpcpy(buffer, object), ": ");
757         } else
758                 b = buffer = newa(char, LINE_MAX);
759
760         vsnprintf(b, LINE_MAX, format, ap);
761
762         return log_dispatch_internal(level, error, file, line, func,
763                                      object_field, object, extra_field, extra, buffer);
764 }
765
766 int log_object_internal(
767                 int level,
768                 int error,
769                 const char *file,
770                 int line,
771                 const char *func,
772                 const char *object_field,
773                 const char *object,
774                 const char *extra_field,
775                 const char *extra,
776                 const char *format, ...) {
777
778         va_list ap;
779         int r;
780
781         va_start(ap, format);
782         r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
783         va_end(ap);
784
785         return r;
786 }
787
788 static void log_assert(
789                 int level,
790                 const char *text,
791                 const char *file,
792                 int line,
793                 const char *func,
794                 const char *format) {
795
796         static char buffer[LINE_MAX];
797         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
798
799         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
800                 return;
801
802         DISABLE_WARNING_FORMAT_NONLITERAL;
803         snprintf(buffer, sizeof buffer, format, text, file, line, func);
804         REENABLE_WARNING;
805
806         log_abort_msg = buffer;
807
808         log_dispatch_internal(level, 0, file, line, func, NULL, NULL, NULL, NULL, buffer);
809 }
810
811 noreturn void log_assert_failed_realm(
812                 LogRealm realm,
813                 const char *text,
814                 const char *file,
815                 int line,
816                 const char *func) {
817         log_assert(LOG_REALM_PLUS_LEVEL(realm, LOG_CRIT), text, file, line, func,
818                    "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
819         abort();
820 }
821
822 noreturn void log_assert_failed_unreachable_realm(
823                 LogRealm realm,
824                 const char *text,
825                 const char *file,
826                 int line,
827                 const char *func) {
828         log_assert(LOG_REALM_PLUS_LEVEL(realm, LOG_CRIT), text, file, line, func,
829                    "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
830         abort();
831 }
832
833 void log_assert_failed_return_realm(
834                 LogRealm realm,
835                 const char *text,
836                 const char *file,
837                 int line,
838                 const char *func) {
839         PROTECT_ERRNO;
840         log_assert(LOG_REALM_PLUS_LEVEL(realm, LOG_DEBUG), text, file, line, func,
841                    "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
842 }
843
844 int log_oom_internal(LogRealm realm, const char *file, int line, const char *func) {
845         log_internal_realm(LOG_REALM_PLUS_LEVEL(realm, LOG_ERR),
846                            ENOMEM, file, line, func, "Out of memory.");
847         return -ENOMEM;
848 }
849
850 int log_format_iovec(
851                 struct iovec *iovec,
852                 unsigned iovec_len,
853                 unsigned *n,
854                 bool newline_separator,
855                 int error,
856                 const char *format,
857                 va_list ap) {
858
859         static const char nl = '\n';
860
861         while (format && *n + 1 < iovec_len) {
862                 va_list aq;
863                 char *m;
864                 int r;
865
866                 /* We need to copy the va_list structure,
867                  * since vasprintf() leaves it afterwards at
868                  * an undefined location */
869
870                 if (error != 0)
871                         errno = error;
872
873                 va_copy(aq, ap);
874                 r = vasprintf(&m, format, aq);
875                 va_end(aq);
876                 if (r < 0)
877                         return -EINVAL;
878
879                 /* Now, jump enough ahead, so that we point to
880                  * the next format string */
881                 VA_FORMAT_ADVANCE(format, ap);
882
883                 IOVEC_SET_STRING(iovec[(*n)++], m);
884
885                 if (newline_separator) {
886                         iovec[*n].iov_base = (char*) &nl;
887                         iovec[*n].iov_len = 1;
888                         (*n)++;
889                 }
890
891                 format = va_arg(ap, char *);
892         }
893         return 0;
894 }
895
896 int log_struct_internal(
897                 int level,
898                 int error,
899                 const char *file,
900                 int line,
901                 const char *func,
902                 const char *format, ...) {
903
904         char buf[LINE_MAX];
905         bool found = false;
906         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
907         PROTECT_ERRNO;
908         va_list ap;
909
910         if (error < 0)
911                 error = -error;
912
913         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
914                 return -error;
915
916         if (log_target == LOG_TARGET_NULL)
917                 return -error;
918
919         if ((level & LOG_FACMASK) == 0)
920                 level = log_facility | LOG_PRI(level);
921
922 #if 0 /// elogind does not support logging to systemd-journald
923         if (IN_SET(log_target, LOG_TARGET_AUTO,
924                                LOG_TARGET_JOURNAL_OR_KMSG,
925                                LOG_TARGET_JOURNAL) &&
926             journal_fd >= 0) {
927                 char header[LINE_MAX];
928                 struct iovec iovec[17] = {};
929                 unsigned n = 0, i;
930                 int r;
931                 struct msghdr mh = {
932                         .msg_iov = iovec,
933                 };
934                 bool fallback = false;
935
936                 /* If the journal is available do structured logging */
937                 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
938                 IOVEC_SET_STRING(iovec[n++], header);
939
940                 va_start(ap, format);
941                 r = log_format_iovec(iovec, ELEMENTSOF(iovec), &n, true, error, format, ap);
942                 if (r < 0)
943                         fallback = true;
944                 else {
945                         mh.msg_iovlen = n;
946                         (void) sendmsg(journal_fd, &mh, MSG_NOSIGNAL);
947                 }
948
949                 va_end(ap);
950                 for (i = 1; i < n; i += 2)
951                         free(iovec[i].iov_base);
952
953                 if (!fallback)
954                         return -error;
955         }
956 #endif // 0
957
958         /* Fallback if journal logging is not available or didn't work. */
959
960         va_start(ap, format);
961         while (format) {
962                 va_list aq;
963
964                 if (error != 0)
965                         errno = error;
966
967                 va_copy(aq, ap);
968                 vsnprintf(buf, sizeof(buf), format, aq);
969                 va_end(aq);
970
971                 if (startswith(buf, "MESSAGE=")) {
972                         found = true;
973                         break;
974                 }
975
976                 VA_FORMAT_ADVANCE(format, ap);
977
978                 format = va_arg(ap, char *);
979         }
980         va_end(ap);
981
982         if (!found)
983                 return -error;
984
985         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
986 }
987
988 int log_set_target_from_string(const char *e) {
989         LogTarget t;
990
991         t = log_target_from_string(e);
992         if (t < 0)
993                 return -EINVAL;
994
995         log_set_target(t);
996         return 0;
997 }
998
999 int log_set_max_level_from_string_realm(LogRealm realm, const char *e) {
1000         int t;
1001
1002         t = log_level_from_string(e);
1003         if (t < 0)
1004                 return -EINVAL;
1005
1006         log_set_max_level_realm(realm, t);
1007         return 0;
1008 }
1009
1010 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1011
1012         /*
1013          * The systemd.log_xyz= settings are parsed by all tools, and
1014          * so is "debug".
1015          *
1016          * However, "quiet" is only parsed by PID 1, and only turns of
1017          * status output to /dev/console, but does not alter the log
1018          * level.
1019          */
1020
1021         if (streq(key, "debug") && !value)
1022                 log_set_max_level(LOG_DEBUG);
1023
1024         else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
1025
1026                 if (proc_cmdline_value_missing(key, value))
1027                         return 0;
1028
1029                 if (log_set_target_from_string(value) < 0)
1030                         log_warning("Failed to parse log target '%s'. Ignoring.", value);
1031
1032         } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
1033
1034                 if (proc_cmdline_value_missing(key, value))
1035                         return 0;
1036
1037                 if (log_set_max_level_from_string(value) < 0)
1038                         log_warning("Failed to parse log level '%s'. Ignoring.", value);
1039
1040         } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
1041
1042                 if (log_show_color_from_string(value ?: "1") < 0)
1043                         log_warning("Failed to parse log color setting '%s'. Ignoring.", value);
1044
1045         } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
1046
1047                 if (log_show_location_from_string(value ?: "1") < 0)
1048                         log_warning("Failed to parse log location setting '%s'. Ignoring.", value);
1049         }
1050
1051         return 0;
1052 }
1053
1054 void log_parse_environment_realm(LogRealm realm) {
1055         const char *e;
1056
1057         if (get_ctty_devnr(0, NULL) < 0)
1058                 /* Only try to read the command line in daemons.  We assume that anything that has a controlling tty is
1059                    user stuff. */
1060                 (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
1061
1062         e = getenv("SYSTEMD_LOG_TARGET");
1063         if (e && log_set_target_from_string(e) < 0)
1064                 log_warning("Failed to parse log target '%s'. Ignoring.", e);
1065
1066         e = getenv("SYSTEMD_LOG_LEVEL");
1067         if (e && log_set_max_level_from_string_realm(realm, e) < 0)
1068                 log_warning("Failed to parse log level '%s'. Ignoring.", e);
1069
1070         e = getenv("SYSTEMD_LOG_COLOR");
1071         if (e && log_show_color_from_string(e) < 0)
1072                 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1073
1074         e = getenv("SYSTEMD_LOG_LOCATION");
1075         if (e && log_show_location_from_string(e) < 0)
1076                 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1077 }
1078
1079 LogTarget log_get_target(void) {
1080         return log_target;
1081 }
1082
1083 int log_get_max_level_realm(LogRealm realm) {
1084         return log_max_level[realm];
1085 }
1086
1087 void log_show_color(bool b) {
1088         show_color = b;
1089 }
1090
1091 bool log_get_show_color(void) {
1092         return show_color;
1093 }
1094
1095 void log_show_location(bool b) {
1096         show_location = b;
1097 }
1098
1099 bool log_get_show_location(void) {
1100         return show_location;
1101 }
1102
1103 int log_show_color_from_string(const char *e) {
1104         int t;
1105
1106         t = parse_boolean(e);
1107         if (t < 0)
1108                 return t;
1109
1110         log_show_color(t);
1111         return 0;
1112 }
1113
1114 int log_show_location_from_string(const char *e) {
1115         int t;
1116
1117         t = parse_boolean(e);
1118         if (t < 0)
1119                 return t;
1120
1121         log_show_location(t);
1122         return 0;
1123 }
1124
1125 bool log_on_console(void) {
1126         if (IN_SET(log_target, LOG_TARGET_CONSOLE,
1127                                LOG_TARGET_CONSOLE_PREFIXED))
1128                 return true;
1129
1130         return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1131 }
1132
1133 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1134         [LOG_TARGET_CONSOLE] = "console",
1135         [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1136         [LOG_TARGET_KMSG] = "kmsg",
1137 #if 0 /// elogind does not support logging to systemd-journald
1138         [LOG_TARGET_JOURNAL] = "journal",
1139         [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1140 #endif // 0
1141         [LOG_TARGET_SYSLOG] = "syslog",
1142         [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1143         [LOG_TARGET_AUTO] = "auto",
1144         [LOG_TARGET_SAFE] = "safe",
1145         [LOG_TARGET_NULL] = "null"
1146 };
1147
1148 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1149
1150 #if 0 /// UNNEEDED by elogind
1151 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1152         if (si->ssi_pid > 0) {
1153                 _cleanup_free_ char *p = NULL;
1154
1155                 get_process_comm(si->ssi_pid, &p);
1156
1157                 log_full(level,
1158                          "Received SIG%s from PID %"PRIu32" (%s).",
1159                          signal_to_string(si->ssi_signo),
1160                          si->ssi_pid, strna(p));
1161         } else
1162                 log_full(level,
1163                          "Received SIG%s.",
1164                          signal_to_string(si->ssi_signo));
1165
1166 }
1167
1168 void log_set_upgrade_syslog_to_journal(bool b) {
1169         upgrade_syslog_to_journal = b;
1170 }
1171 #endif // 0
1172
1173 int log_syntax_internal(
1174                 const char *unit,
1175                 int level,
1176                 const char *config_file,
1177                 unsigned config_line,
1178                 int error,
1179                 const char *file,
1180                 int line,
1181                 const char *func,
1182                 const char *format, ...) {
1183
1184         PROTECT_ERRNO;
1185         char buffer[LINE_MAX];
1186         va_list ap;
1187         const char *unit_fmt = NULL;
1188
1189         if (error < 0)
1190                 error = -error;
1191
1192         if (_likely_(LOG_PRI(level) > log_max_level[LOG_REALM_SYSTEMD]))
1193                 return -error;
1194
1195         if (log_target == LOG_TARGET_NULL)
1196                 return -error;
1197
1198         if (error != 0)
1199                 errno = error;
1200
1201         va_start(ap, format);
1202         vsnprintf(buffer, sizeof(buffer), format, ap);
1203         va_end(ap);
1204
1205         if (unit)
1206                 unit_fmt = getpid() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1207
1208         return log_struct_internal(
1209                         LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD, level),
1210                         error,
1211                         file, line, func,
1212                         "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1213                         "CONFIG_FILE=%s", config_file,
1214                         "CONFIG_LINE=%u", config_line,
1215                         LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
1216                         unit_fmt, unit,
1217                         NULL);
1218 }
1219
1220 #if 0 /// UNNEEDED by elogind
1221 void log_set_always_reopen_console(bool b) {
1222         always_reopen_console = b;
1223 }
1224 #endif // 0