chiark / gitweb /
log: let's make use of the fact that our functions return the negative error code...
[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_cached() == 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_cached() == 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         /* Do not call from library code. */
242
243         /* If we don't use the console we close it here, to not get
244          * killed by SAK. If we don't use syslog we close it here so
245          * that we are not confused by somebody deleting the socket in
246          * the fs. If we don't use /dev/kmsg we still keep it open,
247          * because there is no reason to close it. */
248
249         if (log_target == LOG_TARGET_NULL) {
250                 log_close_journal();
251                 log_close_syslog();
252                 log_close_console();
253                 return 0;
254         }
255
256         if (!IN_SET(log_target, LOG_TARGET_AUTO, LOG_TARGET_SAFE) ||
257             getpid_cached() == 1 ||
258             isatty(STDERR_FILENO) <= 0) {
259
260 #if 0 /// elogind does not support logging to systemd-journald
261                 if (IN_SET(log_target, LOG_TARGET_AUTO,
262                                        LOG_TARGET_JOURNAL_OR_KMSG,
263                                        LOG_TARGET_JOURNAL)) {
264                         r = log_open_journal();
265                         if (r >= 0) {
266                                 log_close_syslog();
267                                 log_close_console();
268                                 return r;
269                         }
270                 }
271 #endif // 0
272
273                 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
274                                        LOG_TARGET_SYSLOG)) {
275                         r = log_open_syslog();
276                         if (r >= 0) {
277                                 log_close_journal();
278                                 log_close_console();
279                                 return r;
280                         }
281                 }
282
283                 if (IN_SET(log_target, LOG_TARGET_AUTO,
284                                        LOG_TARGET_SAFE,
285                                        LOG_TARGET_JOURNAL_OR_KMSG,
286                                        LOG_TARGET_SYSLOG_OR_KMSG,
287                                        LOG_TARGET_KMSG)) {
288                         r = log_open_kmsg();
289                         if (r >= 0) {
290                                 log_close_journal();
291                                 log_close_syslog();
292                                 log_close_console();
293                                 return r;
294                         }
295                 }
296         }
297
298         log_close_journal();
299         log_close_syslog();
300
301         return log_open_console();
302 }
303
304 void log_set_target(LogTarget target) {
305         assert(target >= 0);
306         assert(target < _LOG_TARGET_MAX);
307
308 #if 0 /// elogind does not support logging to systemd-journald
309         if (upgrade_syslog_to_journal) {
310                 if (target == LOG_TARGET_SYSLOG)
311                         target = LOG_TARGET_JOURNAL;
312                 else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
313                         target = LOG_TARGET_JOURNAL_OR_KMSG;
314         }
315 #endif // 0
316
317         log_target = target;
318 }
319
320 void log_close(void) {
321         /* Do not call from library code. */
322
323         log_close_journal();
324         log_close_syslog();
325         log_close_kmsg();
326         log_close_console();
327 }
328
329 #if 0 /// UNNEEDED by elogind
330 void log_forget_fds(void) {
331         /* Do not call from library code. */
332
333         console_fd = kmsg_fd = syslog_fd = journal_fd = -1;
334 }
335 #endif // 0
336
337 void log_set_max_level_realm(LogRealm realm, int level) {
338         assert((level & LOG_PRIMASK) == level);
339         assert(realm < ELEMENTSOF(log_max_level));
340
341         log_max_level[realm] = level;
342 }
343
344 void log_set_facility(int facility) {
345         log_facility = facility;
346 }
347
348 static int write_to_console(
349                 int level,
350                 int error,
351                 const char *file,
352                 int line,
353                 const char *func,
354                 const char *buffer) {
355
356         char location[256], prefix[1 + DECIMAL_STR_MAX(int) + 2];
357         struct iovec iovec[6] = {};
358         unsigned n = 0;
359         bool highlight;
360
361         if (console_fd < 0)
362                 return 0;
363
364         if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
365                 xsprintf(prefix, "<%i>", level);
366                 iovec[n++] = IOVEC_MAKE_STRING(prefix);
367         }
368
369         highlight = LOG_PRI(level) <= LOG_ERR && show_color;
370
371         if (show_location) {
372                 snprintf(location, sizeof(location), "(%s:%i) ", file, line);
373                 iovec[n++] = IOVEC_MAKE_STRING(location);
374         }
375
376         if (highlight)
377                 iovec[n++] = IOVEC_MAKE_STRING(ANSI_HIGHLIGHT_RED);
378         iovec[n++] = IOVEC_MAKE_STRING(buffer);
379         if (highlight)
380                 iovec[n++] = IOVEC_MAKE_STRING(ANSI_NORMAL);
381         iovec[n++] = IOVEC_MAKE_STRING("\n");
382
383         if (writev(console_fd, iovec, n) < 0) {
384
385                 if (errno == EIO && getpid_cached() == 1) {
386
387                         /* If somebody tried to kick us from our
388                          * console tty (via vhangup() or suchlike),
389                          * try to reconnect */
390
391                         log_close_console();
392                         log_open_console();
393
394                         if (console_fd < 0)
395                                 return 0;
396
397                         if (writev(console_fd, iovec, n) < 0)
398                                 return -errno;
399                 } else
400                         return -errno;
401         }
402
403         return 1;
404 }
405
406 static int write_to_syslog(
407                 int level,
408                 int error,
409                 const char *file,
410                 int line,
411                 const char *func,
412                 const char *buffer) {
413
414         char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
415              header_time[64],
416              header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
417         struct iovec iovec[5] = {};
418         struct msghdr msghdr = {
419                 .msg_iov = iovec,
420                 .msg_iovlen = ELEMENTSOF(iovec),
421         };
422         time_t t;
423         struct tm *tm;
424
425         if (syslog_fd < 0)
426                 return 0;
427
428         xsprintf(header_priority, "<%i>", level);
429
430         t = (time_t) (now(CLOCK_REALTIME) / USEC_PER_SEC);
431         tm = localtime(&t);
432         if (!tm)
433                 return -EINVAL;
434
435         if (strftime(header_time, sizeof(header_time), "%h %e %T ", tm) <= 0)
436                 return -EINVAL;
437
438         xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
439
440         iovec[0] = IOVEC_MAKE_STRING(header_priority);
441         iovec[1] = IOVEC_MAKE_STRING(header_time);
442         iovec[2] = IOVEC_MAKE_STRING(program_invocation_short_name);
443         iovec[3] = IOVEC_MAKE_STRING(header_pid);
444         iovec[4] = IOVEC_MAKE_STRING(buffer);
445
446         /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
447         if (syslog_is_stream)
448                 iovec[4].iov_len++;
449
450         for (;;) {
451                 ssize_t n;
452
453                 n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
454                 if (n < 0)
455                         return -errno;
456
457                 if (!syslog_is_stream ||
458                     (size_t) n >= IOVEC_TOTAL_SIZE(iovec, ELEMENTSOF(iovec)))
459                         break;
460
461                 IOVEC_INCREMENT(iovec, ELEMENTSOF(iovec), n);
462         }
463
464         return 1;
465 }
466
467 static int write_to_kmsg(
468                 int level,
469                 int error,
470                 const char *file,
471                 int line,
472                 const char *func,
473                 const char *buffer) {
474
475         char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
476              header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
477         struct iovec iovec[5] = {};
478
479         if (kmsg_fd < 0)
480                 return 0;
481
482         xsprintf(header_priority, "<%i>", level);
483         xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
484
485         iovec[0] = IOVEC_MAKE_STRING(header_priority);
486         iovec[1] = IOVEC_MAKE_STRING(program_invocation_short_name);
487         iovec[2] = IOVEC_MAKE_STRING(header_pid);
488         iovec[3] = IOVEC_MAKE_STRING(buffer);
489         iovec[4] = IOVEC_MAKE_STRING("\n");
490
491         if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
492                 return -errno;
493
494         return 1;
495 }
496
497 static int log_do_header(
498                 char *header,
499                 size_t size,
500                 int level,
501                 int error,
502                 const char *file, int line, const char *func,
503                 const char *object_field, const char *object,
504                 const char *extra_field, const char *extra) {
505
506         snprintf(header, size,
507                  "PRIORITY=%i\n"
508                  "SYSLOG_FACILITY=%i\n"
509                  "%s%s%s"
510                  "%s%.*i%s"
511                  "%s%s%s"
512                  "%s%.*i%s"
513                  "%s%s%s"
514                  "%s%s%s"
515                  "SYSLOG_IDENTIFIER=%s\n",
516                  LOG_PRI(level),
517                  LOG_FAC(level),
518                  isempty(file) ? "" : "CODE_FILE=",
519                  isempty(file) ? "" : file,
520                  isempty(file) ? "" : "\n",
521                  line ? "CODE_LINE=" : "",
522                  line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
523                  line ? "\n" : "",
524                  isempty(func) ? "" : "CODE_FUNC=",
525                  isempty(func) ? "" : func,
526                  isempty(func) ? "" : "\n",
527                  error ? "ERRNO=" : "",
528                  error ? 1 : 0, error,
529                  error ? "\n" : "",
530                  isempty(object) ? "" : object_field,
531                  isempty(object) ? "" : object,
532                  isempty(object) ? "" : "\n",
533                  isempty(extra) ? "" : extra_field,
534                  isempty(extra) ? "" : extra,
535                  isempty(extra) ? "" : "\n",
536                  program_invocation_short_name);
537
538         return 0;
539 }
540
541 #if 0 /// UNNEEDED by elogind
542 static int write_to_journal(
543                 int level,
544                 int error,
545                 const char *file,
546                 int line,
547                 const char *func,
548                 const char *object_field,
549                 const char *object,
550                 const char *extra_field,
551                 const char *extra,
552                 const char *buffer) {
553
554         char header[LINE_MAX];
555         struct iovec iovec[4] = {};
556         struct msghdr mh = {};
557
558         if (journal_fd < 0)
559                 return 0;
560
561         log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
562
563         iovec[0] = IOVEC_MAKE_STRING(header);
564         iovec[1] = IOVEC_MAKE_STRING("MESSAGE=");
565         iovec[2] = IOVEC_MAKE_STRING(buffer);
566         iovec[3] = IOVEC_MAKE_STRING("\n");
567
568         mh.msg_iov = iovec;
569         mh.msg_iovlen = ELEMENTSOF(iovec);
570
571         if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) < 0)
572                 return -errno;
573
574         return 1;
575 }
576 #endif // 0
577
578 int log_dispatch_internal(
579                 int level,
580                 int error,
581                 const char *file,
582                 int line,
583                 const char *func,
584                 const char *object_field,
585                 const char *object,
586                 const char *extra,
587                 const char *extra_field,
588                 char *buffer) {
589
590         assert(buffer);
591
592         if (error < 0)
593                 error = -error;
594
595         if (log_target == LOG_TARGET_NULL)
596                 return -error;
597
598         /* Patch in LOG_DAEMON facility if necessary */
599         if ((level & LOG_FACMASK) == 0)
600                 level = log_facility | LOG_PRI(level);
601
602         do {
603                 char *e;
604                 int k = 0;
605
606                 buffer += strspn(buffer, NEWLINE);
607
608                 if (buffer[0] == 0)
609                         break;
610
611                 if ((e = strpbrk(buffer, NEWLINE)))
612                         *(e++) = 0;
613
614 #if 0 /// elogind does not support logging to systemd-journald
615                 if (IN_SET(log_target, LOG_TARGET_AUTO,
616                                        LOG_TARGET_JOURNAL_OR_KMSG,
617                                        LOG_TARGET_JOURNAL)) {
618
619                         k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
620                         if (k < 0) {
621                                 if (k != -EAGAIN)
622                                         log_close_journal();
623                                 log_open_kmsg();
624                         }
625                 }
626 #endif // 0
627
628                 if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
629                                        LOG_TARGET_SYSLOG)) {
630
631                         k = write_to_syslog(level, error, file, line, func, buffer);
632                         if (k < 0) {
633                                 if (k != -EAGAIN)
634                                         log_close_syslog();
635                                 log_open_kmsg();
636                         }
637                 }
638
639                 if (k <= 0 &&
640                     IN_SET(log_target, LOG_TARGET_AUTO,
641                                        LOG_TARGET_SAFE,
642                                        LOG_TARGET_SYSLOG_OR_KMSG,
643                                        LOG_TARGET_JOURNAL_OR_KMSG,
644                                        LOG_TARGET_KMSG)) {
645
646                         k = write_to_kmsg(level, error, file, line, func, buffer);
647                         if (k < 0) {
648                                 log_close_kmsg();
649                                 log_open_console();
650                         }
651                 }
652
653                 if (k <= 0)
654                         (void) write_to_console(level, error, file, line, func, buffer);
655
656                 buffer = e;
657         } while (buffer);
658
659         return -error;
660 }
661
662 int log_dump_internal(
663                 int level,
664                 int error,
665                 const char *file,
666                 int line,
667                 const char *func,
668                 char *buffer) {
669
670         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
671         PROTECT_ERRNO;
672
673         /* This modifies the buffer... */
674
675         if (error < 0)
676                 error = -error;
677
678         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
679                 return -error;
680
681         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
682 }
683
684 int log_internalv_realm(
685                 int level,
686                 int error,
687                 const char *file,
688                 int line,
689                 const char *func,
690                 const char *format,
691                 va_list ap) {
692
693         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
694         char buffer[LINE_MAX];
695         PROTECT_ERRNO;
696
697         if (error < 0)
698                 error = -error;
699
700         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
701                 return -error;
702
703         /* Make sure that %m maps to the specified error */
704         if (error != 0)
705                 errno = error;
706
707         vsnprintf(buffer, sizeof(buffer), format, ap);
708
709         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
710 }
711
712 int log_internal_realm(
713                 int level,
714                 int error,
715                 const char *file,
716                 int line,
717                 const char *func,
718                 const char *format, ...) {
719
720         va_list ap;
721         int r;
722
723         va_start(ap, format);
724         r = log_internalv_realm(level, error, file, line, func, format, ap);
725         va_end(ap);
726
727         return r;
728 }
729
730 int log_object_internalv(
731                 int level,
732                 int error,
733                 const char *file,
734                 int line,
735                 const char *func,
736                 const char *object_field,
737                 const char *object,
738                 const char *extra_field,
739                 const char *extra,
740                 const char *format,
741                 va_list ap) {
742
743         PROTECT_ERRNO;
744         char *buffer, *b;
745
746         if (error < 0)
747                 error = -error;
748
749         if (_likely_(LOG_PRI(level) > log_max_level[LOG_REALM_SYSTEMD]))
750                 return -error;
751
752         /* Make sure that %m maps to the specified error */
753         if (error != 0)
754                 errno = error;
755
756         /* Prepend the object name before the message */
757         if (object) {
758                 size_t n;
759
760                 n = strlen(object);
761                 buffer = newa(char, n + 2 + LINE_MAX);
762                 b = stpcpy(stpcpy(buffer, object), ": ");
763         } else
764                 b = buffer = newa(char, LINE_MAX);
765
766         vsnprintf(b, LINE_MAX, format, ap);
767
768         return log_dispatch_internal(level, error, file, line, func,
769                                      object_field, object, extra_field, extra, buffer);
770 }
771
772 int log_object_internal(
773                 int level,
774                 int error,
775                 const char *file,
776                 int line,
777                 const char *func,
778                 const char *object_field,
779                 const char *object,
780                 const char *extra_field,
781                 const char *extra,
782                 const char *format, ...) {
783
784         va_list ap;
785         int r;
786
787         va_start(ap, format);
788         r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
789         va_end(ap);
790
791         return r;
792 }
793
794 static void log_assert(
795                 int level,
796                 const char *text,
797                 const char *file,
798                 int line,
799                 const char *func,
800                 const char *format) {
801
802         static char buffer[LINE_MAX];
803         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
804
805         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
806                 return;
807
808         DISABLE_WARNING_FORMAT_NONLITERAL;
809         snprintf(buffer, sizeof buffer, format, text, file, line, func);
810         REENABLE_WARNING;
811
812         log_abort_msg = buffer;
813
814         log_dispatch_internal(level, 0, file, line, func, NULL, NULL, NULL, NULL, buffer);
815 }
816
817 noreturn void log_assert_failed_realm(
818                 LogRealm realm,
819                 const char *text,
820                 const char *file,
821                 int line,
822                 const char *func) {
823         log_open();
824         log_assert(LOG_REALM_PLUS_LEVEL(realm, LOG_CRIT), text, file, line, func,
825                    "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
826         abort();
827 }
828
829 noreturn void log_assert_failed_unreachable_realm(
830                 LogRealm realm,
831                 const char *text,
832                 const char *file,
833                 int line,
834                 const char *func) {
835         log_open();
836         log_assert(LOG_REALM_PLUS_LEVEL(realm, LOG_CRIT), text, file, line, func,
837                    "Code should not be reached '%s' at %s:%u, function %s(). Aborting.");
838         abort();
839 }
840
841 void log_assert_failed_return_realm(
842                 LogRealm realm,
843                 const char *text,
844                 const char *file,
845                 int line,
846                 const char *func) {
847         PROTECT_ERRNO;
848         log_assert(LOG_REALM_PLUS_LEVEL(realm, LOG_DEBUG), text, file, line, func,
849                    "Assertion '%s' failed at %s:%u, function %s(). Ignoring.");
850 }
851
852 int log_oom_internal(LogRealm realm, const char *file, int line, const char *func) {
853         return log_internal_realm(LOG_REALM_PLUS_LEVEL(realm, LOG_ERR),
854                                   ENOMEM, file, line, func, "Out of memory.");
855 }
856
857 int log_format_iovec(
858                 struct iovec *iovec,
859                 unsigned iovec_len,
860                 unsigned *n,
861                 bool newline_separator,
862                 int error,
863                 const char *format,
864                 va_list ap) {
865
866         static const char nl = '\n';
867
868         while (format && *n + 1 < iovec_len) {
869                 va_list aq;
870                 char *m;
871                 int r;
872
873                 /* We need to copy the va_list structure,
874                  * since vasprintf() leaves it afterwards at
875                  * an undefined location */
876
877                 if (error != 0)
878                         errno = error;
879
880                 va_copy(aq, ap);
881                 r = vasprintf(&m, format, aq);
882                 va_end(aq);
883                 if (r < 0)
884                         return -EINVAL;
885
886                 /* Now, jump enough ahead, so that we point to
887                  * the next format string */
888                 VA_FORMAT_ADVANCE(format, ap);
889
890                 iovec[(*n)++] = IOVEC_MAKE_STRING(m);
891
892                 if (newline_separator) {
893                         iovec[*n].iov_base = (char*) &nl;
894                         iovec[*n].iov_len = 1;
895                         (*n)++;
896                 }
897
898                 format = va_arg(ap, char *);
899         }
900         return 0;
901 }
902
903 int log_struct_internal(
904                 int level,
905                 int error,
906                 const char *file,
907                 int line,
908                 const char *func,
909                 const char *format, ...) {
910
911         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
912         char buf[LINE_MAX];
913         bool found = false;
914         PROTECT_ERRNO;
915         va_list ap;
916
917         if (error < 0)
918                 error = -error;
919
920         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
921                 return -error;
922
923         if (log_target == LOG_TARGET_NULL)
924                 return -error;
925
926         if ((level & LOG_FACMASK) == 0)
927                 level = log_facility | LOG_PRI(level);
928
929 #if 0 /// elogind does not support logging to systemd-journald
930         if (IN_SET(log_target, LOG_TARGET_AUTO,
931                                LOG_TARGET_JOURNAL_OR_KMSG,
932                                LOG_TARGET_JOURNAL) &&
933             journal_fd >= 0) {
934                 char header[LINE_MAX];
935                 struct iovec iovec[17] = {};
936                 unsigned n = 0, i;
937                 int r;
938                 struct msghdr mh = {
939                         .msg_iov = iovec,
940                 };
941                 bool fallback = false;
942
943                 /* If the journal is available do structured logging */
944                 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
945                 iovec[n++] = IOVEC_MAKE_STRING(header);
946
947                 va_start(ap, format);
948                 r = log_format_iovec(iovec, ELEMENTSOF(iovec), &n, true, error, format, ap);
949                 if (r < 0)
950                         fallback = true;
951                 else {
952                         mh.msg_iovlen = n;
953                         (void) sendmsg(journal_fd, &mh, MSG_NOSIGNAL);
954                 }
955
956                 va_end(ap);
957                 for (i = 1; i < n; i += 2)
958                         free(iovec[i].iov_base);
959
960                 if (!fallback)
961                         return -error;
962         }
963 #endif // 0
964
965         /* Fallback if journal logging is not available or didn't work. */
966
967         va_start(ap, format);
968         while (format) {
969                 va_list aq;
970
971                 if (error != 0)
972                         errno = error;
973
974                 va_copy(aq, ap);
975                 vsnprintf(buf, sizeof(buf), format, aq);
976                 va_end(aq);
977
978                 if (startswith(buf, "MESSAGE=")) {
979                         found = true;
980                         break;
981                 }
982
983                 VA_FORMAT_ADVANCE(format, ap);
984
985                 format = va_arg(ap, char *);
986         }
987         va_end(ap);
988
989         if (!found)
990                 return -error;
991
992         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
993 }
994
995 int log_struct_iovec_internal(
996                 int level,
997                 int error,
998                 const char *file,
999                 int line,
1000                 const char *func,
1001                 const struct iovec input_iovec[],
1002                 size_t n_input_iovec) {
1003
1004         LogRealm realm = LOG_REALM_REMOVE_LEVEL(level);
1005         PROTECT_ERRNO;
1006         size_t i;
1007         char *m;
1008
1009         if (error < 0)
1010                 error = -error;
1011
1012         if (_likely_(LOG_PRI(level) > log_max_level[realm]))
1013                 return -error;
1014
1015         if (log_target == LOG_TARGET_NULL)
1016                 return -error;
1017
1018         if ((level & LOG_FACMASK) == 0)
1019                 level = log_facility | LOG_PRI(level);
1020
1021         if (IN_SET(log_target, LOG_TARGET_AUTO,
1022                                LOG_TARGET_JOURNAL_OR_KMSG,
1023                                LOG_TARGET_JOURNAL) &&
1024             journal_fd >= 0) {
1025
1026                 struct iovec iovec[1 + n_input_iovec*2];
1027                 char header[LINE_MAX];
1028                 struct msghdr mh = {
1029                         .msg_iov = iovec,
1030                         .msg_iovlen = 1 + n_input_iovec*2,
1031                 };
1032
1033                 log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
1034                 iovec[0] = IOVEC_MAKE_STRING(header);
1035
1036                 for (i = 0; i < n_input_iovec; i++) {
1037                         iovec[1+i*2] = input_iovec[i];
1038                         iovec[1+i*2+1] = IOVEC_MAKE_STRING("\n");
1039                 }
1040
1041                 if (sendmsg(journal_fd, &mh, MSG_NOSIGNAL) >= 0)
1042                         return -error;
1043         }
1044
1045         for (i = 0; i < n_input_iovec; i++) {
1046                 if (input_iovec[i].iov_len < strlen("MESSAGE="))
1047                         continue;
1048
1049                 if (memcmp(input_iovec[i].iov_base, "MESSAGE=", strlen("MESSAGE=")) == 0)
1050                         break;
1051         }
1052
1053         if (_unlikely_(i >= n_input_iovec)) /* Couldn't find MESSAGE=? */
1054                 return -error;
1055
1056         m = strndupa(input_iovec[i].iov_base + strlen("MESSAGE="),
1057                      input_iovec[i].iov_len - strlen("MESSAGE="));
1058
1059         return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, m);
1060 }
1061
1062 int log_set_target_from_string(const char *e) {
1063         LogTarget t;
1064
1065         t = log_target_from_string(e);
1066         if (t < 0)
1067                 return -EINVAL;
1068
1069         log_set_target(t);
1070         return 0;
1071 }
1072
1073 int log_set_max_level_from_string_realm(LogRealm realm, const char *e) {
1074         int t;
1075
1076         t = log_level_from_string(e);
1077         if (t < 0)
1078                 return -EINVAL;
1079
1080         log_set_max_level_realm(realm, t);
1081         return 0;
1082 }
1083
1084 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1085
1086         /*
1087          * The systemd.log_xyz= settings are parsed by all tools, and
1088          * so is "debug".
1089          *
1090          * However, "quiet" is only parsed by PID 1, and only turns of
1091          * status output to /dev/console, but does not alter the log
1092          * level.
1093          */
1094
1095         if (streq(key, "debug") && !value)
1096                 log_set_max_level(LOG_DEBUG);
1097
1098         else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
1099
1100                 if (proc_cmdline_value_missing(key, value))
1101                         return 0;
1102
1103                 if (log_set_target_from_string(value) < 0)
1104                         log_warning("Failed to parse log target '%s'. Ignoring.", value);
1105
1106         } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
1107
1108                 if (proc_cmdline_value_missing(key, value))
1109                         return 0;
1110
1111                 if (log_set_max_level_from_string(value) < 0)
1112                         log_warning("Failed to parse log level '%s'. Ignoring.", value);
1113
1114         } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
1115
1116                 if (log_show_color_from_string(value ?: "1") < 0)
1117                         log_warning("Failed to parse log color setting '%s'. Ignoring.", value);
1118
1119         } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
1120
1121                 if (log_show_location_from_string(value ?: "1") < 0)
1122                         log_warning("Failed to parse log location setting '%s'. Ignoring.", value);
1123         }
1124
1125         return 0;
1126 }
1127
1128 void log_parse_environment_realm(LogRealm realm) {
1129         /* Do not call from library code. */
1130
1131         const char *e;
1132
1133         if (get_ctty_devnr(0, NULL) < 0)
1134                 /* Only try to read the command line in daemons.  We assume that anything that has a controlling tty is
1135                    user stuff. */
1136                 (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
1137
1138         e = getenv("SYSTEMD_LOG_TARGET");
1139         if (e && log_set_target_from_string(e) < 0)
1140                 log_warning("Failed to parse log target '%s'. Ignoring.", e);
1141
1142         e = getenv("SYSTEMD_LOG_LEVEL");
1143         if (e && log_set_max_level_from_string_realm(realm, e) < 0)
1144                 log_warning("Failed to parse log level '%s'. Ignoring.", e);
1145
1146         e = getenv("SYSTEMD_LOG_COLOR");
1147         if (e && log_show_color_from_string(e) < 0)
1148                 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1149
1150         e = getenv("SYSTEMD_LOG_LOCATION");
1151         if (e && log_show_location_from_string(e) < 0)
1152                 log_warning("Failed to parse bool '%s'. Ignoring.", e);
1153 }
1154
1155 LogTarget log_get_target(void) {
1156         return log_target;
1157 }
1158
1159 int log_get_max_level_realm(LogRealm realm) {
1160         return log_max_level[realm];
1161 }
1162
1163 void log_show_color(bool b) {
1164         show_color = b;
1165 }
1166
1167 bool log_get_show_color(void) {
1168         return show_color;
1169 }
1170
1171 void log_show_location(bool b) {
1172         show_location = b;
1173 }
1174
1175 bool log_get_show_location(void) {
1176         return show_location;
1177 }
1178
1179 int log_show_color_from_string(const char *e) {
1180         int t;
1181
1182         t = parse_boolean(e);
1183         if (t < 0)
1184                 return t;
1185
1186         log_show_color(t);
1187         return 0;
1188 }
1189
1190 int log_show_location_from_string(const char *e) {
1191         int t;
1192
1193         t = parse_boolean(e);
1194         if (t < 0)
1195                 return t;
1196
1197         log_show_location(t);
1198         return 0;
1199 }
1200
1201 bool log_on_console(void) {
1202         if (IN_SET(log_target, LOG_TARGET_CONSOLE,
1203                                LOG_TARGET_CONSOLE_PREFIXED))
1204                 return true;
1205
1206         return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
1207 }
1208
1209 static const char *const log_target_table[_LOG_TARGET_MAX] = {
1210         [LOG_TARGET_CONSOLE] = "console",
1211         [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1212         [LOG_TARGET_KMSG] = "kmsg",
1213 #if 0 /// elogind does not support logging to systemd-journald
1214         [LOG_TARGET_JOURNAL] = "journal",
1215         [LOG_TARGET_JOURNAL_OR_KMSG] = "journal-or-kmsg",
1216 #endif // 0
1217         [LOG_TARGET_SYSLOG] = "syslog",
1218         [LOG_TARGET_SYSLOG_OR_KMSG] = "syslog-or-kmsg",
1219         [LOG_TARGET_AUTO] = "auto",
1220         [LOG_TARGET_SAFE] = "safe",
1221         [LOG_TARGET_NULL] = "null"
1222 };
1223
1224 DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
1225
1226 #if 0 /// UNNEEDED by elogind
1227 void log_received_signal(int level, const struct signalfd_siginfo *si) {
1228         if (si->ssi_pid > 0) {
1229                 _cleanup_free_ char *p = NULL;
1230
1231                 get_process_comm(si->ssi_pid, &p);
1232
1233                 log_full(level,
1234                          "Received SIG%s from PID %"PRIu32" (%s).",
1235                          signal_to_string(si->ssi_signo),
1236                          si->ssi_pid, strna(p));
1237         } else
1238                 log_full(level,
1239                          "Received SIG%s.",
1240                          signal_to_string(si->ssi_signo));
1241
1242 }
1243
1244 void log_set_upgrade_syslog_to_journal(bool b) {
1245         upgrade_syslog_to_journal = b;
1246 }
1247 #endif // 0
1248
1249 int log_syntax_internal(
1250                 const char *unit,
1251                 int level,
1252                 const char *config_file,
1253                 unsigned config_line,
1254                 int error,
1255                 const char *file,
1256                 int line,
1257                 const char *func,
1258                 const char *format, ...) {
1259
1260         PROTECT_ERRNO;
1261         char buffer[LINE_MAX];
1262         va_list ap;
1263         const char *unit_fmt = NULL;
1264
1265         if (error < 0)
1266                 error = -error;
1267
1268         if (_likely_(LOG_PRI(level) > log_max_level[LOG_REALM_SYSTEMD]))
1269                 return -error;
1270
1271         if (log_target == LOG_TARGET_NULL)
1272                 return -error;
1273
1274         if (error != 0)
1275                 errno = error;
1276
1277         va_start(ap, format);
1278         vsnprintf(buffer, sizeof(buffer), format, ap);
1279         va_end(ap);
1280
1281         if (unit)
1282                 unit_fmt = getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
1283
1284         return log_struct_internal(
1285                         LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD, level),
1286                         error,
1287                         file, line, func,
1288                         "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1289                         "CONFIG_FILE=%s", config_file,
1290                         "CONFIG_LINE=%u", config_line,
1291                         LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
1292                         unit_fmt, unit,
1293                         NULL);
1294 }
1295
1296 #if 0 /// UNNEEDED by elogind
1297 void log_set_always_reopen_console(bool b) {
1298         always_reopen_console = b;
1299 }
1300 #endif // 0