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