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