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