Debian Codegraph @

src/journal/journald-stream.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4 #include <sys/stat.h>
5
6 #include "sd-event.h"
7
8 #include "alloc-util.h"
9 #include "dirent-util.h"
10 #include "env-file.h"
11 #include "errno-util.h"
12 #include "escape.h"
13 #include "fd-util.h"
14 #include "fdset.h"
15 #include "fileio.h"
16 #include "fs-util.h"
17 #include "iovec-util.h"
18 #include "journal-internal.h"
19 #include "journald-client.h"
20 #include "journald-console.h"
21 #include "journald-context.h"
22 #include "journald-kmsg.h"
23 #include "journald-manager.h"
24 #include "journald-stream.h"
25 #include "journald-sync.h"
26 #include "journald-syslog.h"
27 #include "journald-wall.h"
28 #include "log.h"
29 #include "log-ratelimit.h"
30 #include "mkdir.h"
31 #include "parse-util.h"
32 #include "process-util.h"
33 #include "selinux-util.h"
34 #include "socket-util.h"
35 #include "stdio-util.h"
36 #include "string-util.h"
37 #include "syslog-util.h"
38 #include "tmpfile-util.h"
39 #include "unit-name.h"
40
41 #define STDOUT_STREAMS_MAX (64*1024)
42
43 /* During the "setup" protocol phase of the stream logic let's define a different maximum line length than
44 * during the actual operational phase. We want to allow users to specify very short line lengths after all,
45 * but the unit name we embed in the setup protocol might be longer than that. Hence, during the setup phase
46 * let's enforce a line length matching the maximum unit name length (255) */
47 #define STDOUT_STREAM_SETUP_PROTOCOL_LINE_MAX (UNIT_NAME_MAX-1U)
48
49 /* The different types of log record terminators: a real \n was read, a NUL character was read, the maximum line length
50 * was reached, or the end of the stream was reached */
51
52 typedef enum LineBreak {
53 LINE_BREAK_NEWLINE,
54 LINE_BREAK_NUL,
55 LINE_BREAK_LINE_MAX,
56 LINE_BREAK_EOF,
57 LINE_BREAK_PID_CHANGE,
58 _LINE_BREAK_MAX,
59 _LINE_BREAK_INVALID = -EINVAL,
60 } LineBreak;
61
62 StdoutStream* stdout_stream_free(StdoutStream *s) {
63 if (!s)
64 return NULL;
65
66 while (s->stream_sync_reqs)
67 stream_sync_req_free(s->stream_sync_reqs);
68
69 if (s->manager) {
70 if (s->context)
71 client_context_release(s->manager, s->context);
72
73 assert(s->manager->n_stdout_streams > 0);
74 s->manager->n_stdout_streams--;
75 LIST_REMOVE(stdout_stream, s->manager->stdout_streams, s);
76
77 if (s->in_notify_queue)
78 LIST_REMOVE(stdout_stream_notify_queue, s->manager->stdout_streams_notify_queue, s);
79 }
80
81 sd_event_source_disable_unref(s->event_source);
82 safe_close(s->fd);
83 free(s->label);
84 free(s->identifier);
85 free(s->unit_id);
86 free(s->state_file);
87 free(s->buffer);
88
89 return mfree(s);
90 }
91
92 DEFINE_TRIVIAL_CLEANUP_FUNC(StdoutStream*, stdout_stream_free);
93
94 void stdout_stream_terminate(StdoutStream *s) {
95 if (!s)
96 return;
97
98 if (s->state_file)
99 (void) unlink(s->state_file);
100
101 StreamSyncReq *ssr;
102 while ((ssr = s->stream_sync_reqs)) {
103 SyncReq *req = ssr->req;
104 stream_sync_req_free(TAKE_PTR(ssr));
105 sync_req_revalidate(TAKE_PTR(req));
106 }
107
108 Manager *manager = s->manager;
109 stdout_stream_free(TAKE_PTR(s));
110 (void) manager_start_or_stop_idle_timer(manager); /* Maybe we are idle now? */
111 }
112
113 static int stdout_stream_save(StdoutStream *s) {
114 _cleanup_(unlink_and_freep) char *temp_path = NULL;
115 _cleanup_fclose_ FILE *f = NULL;
116 int r;
117
118 assert(s);
119
120 if (s->state != STDOUT_STREAM_RUNNING)
121 return 0;
122
123 if (!s->state_file) {
124 struct stat st;
125
126 r = fstat(s->fd, &st);
127 if (r < 0)
128 return log_ratelimit_warning_errno(errno, JOURNAL_LOG_RATELIMIT,
129 "Failed to stat connected stream: %m");
130
131 /* We use device and inode numbers as identifier for the stream */
132 r = asprintf(&s->state_file, "%s/streams/%lu:%lu", s->manager->runtime_directory, (unsigned long) st.st_dev, (unsigned long) st.st_ino);
133 if (r < 0)
134 return log_oom();
135 }
136
137 (void) mkdir_parents(s->state_file, 0755);
138
139 r = fopen_temporary(s->state_file, &f, &temp_path);
140 if (r < 0)
141 goto fail;
142
143 fprintf(f,
144 "# This is private data. Do not parse\n"
145 "PRIORITY=%i\n"
146 "LEVEL_PREFIX=%i\n"
147 "FORWARD_TO_SYSLOG=%i\n"
148 "FORWARD_TO_KMSG=%i\n"
149 "FORWARD_TO_CONSOLE=%i\n"
150 "STREAM_ID=%s\n",
151 s->priority,
152 s->level_prefix,
153 s->forward_to_syslog,
154 s->forward_to_kmsg,
155 s->forward_to_console,
156 s->id_field + STRLEN("_STREAM_ID="));
157
158 if (!isempty(s->identifier)) {
159 _cleanup_free_ char *escaped = NULL;
160
161 escaped = cescape(s->identifier);
162 if (!escaped) {
163 r = -ENOMEM;
164 goto fail;
165 }
166
167 fprintf(f, "IDENTIFIER=%s\n", escaped);
168 }
169
170 if (!isempty(s->unit_id)) {
171 _cleanup_free_ char *escaped = NULL;
172
173 escaped = cescape(s->unit_id);
174 if (!escaped) {
175 r = -ENOMEM;
176 goto fail;
177 }
178
179 fprintf(f, "UNIT=%s\n", escaped);
180 }
181
182 r = fflush_and_check(f);
183 if (r < 0)
184 goto fail;
185
186 r = RET_NERRNO(rename(temp_path, s->state_file));
187 if (r < 0)
188 goto fail;
189
190 temp_path = mfree(temp_path);
191
192 if (!s->fdstore && !s->in_notify_queue) {
193 LIST_PREPEND(stdout_stream_notify_queue, s->manager->stdout_streams_notify_queue, s);
194 s->in_notify_queue = true;
195
196 if (s->manager->notify_event_source) {
197 r = sd_event_source_set_enabled(s->manager->notify_event_source, SD_EVENT_ON);
198 if (r < 0)
199 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to enable notify event source: %m");
200 }
201 }
202
203 return 0;
204
205 fail:
206 (void) unlink(s->state_file);
207 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
208 "Failed to save stream data %s: %m", s->state_file);
209 }
210
211 static int stdout_stream_log(
212 StdoutStream *s,
213 const char *p,
214 LineBreak line_break) {
215
216 struct iovec *iovec;
217 int priority;
218 char syslog_priority[] = "PRIORITY=\0";
219 char syslog_facility[STRLEN("SYSLOG_FACILITY=") + DECIMAL_STR_MAX(int) + 1];
220 _cleanup_free_ char *message = NULL, *syslog_identifier = NULL;
221 size_t n = 0, m;
222 int r;
223
224 assert(s);
225 assert(p);
226
227 assert(line_break >= 0);
228 assert(line_break < _LINE_BREAK_MAX);
229
230 if (s->context)
231 client_context_maybe_refresh(s->manager, s->context, /* ucred= */ NULL, /* label= */ NULL, /* unit_id= */ NULL, USEC_INFINITY);
232 else if (pid_is_valid(s->ucred.pid)) {
233 r = client_context_acquire(s->manager, s->ucred.pid, &s->ucred, s->label, s->unit_id, &s->context);
234 if (r < 0)
235 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
236 "Failed to acquire client context, ignoring: %m");
237 }
238
239 priority = s->priority;
240
241 if (s->level_prefix)
242 syslog_parse_priority(&p, &priority, false);
243
244 if (!client_context_test_priority(s->context, priority))
245 return 0;
246
247 if (isempty(p))
248 return 0;
249
250 r = client_context_check_keep_log(s->context, p, strlen(p));
251 if (r <= 0)
252 return r;
253
254 if (s->forward_to_syslog || s->manager->config.forward_to_syslog)
255 manager_forward_syslog(s->manager, syslog_fixup_facility(priority), s->identifier, p, &s->ucred, NULL);
256
257 if (s->forward_to_kmsg || s->manager->config.forward_to_kmsg)
258 manager_forward_kmsg(s->manager, priority, s->identifier, p, &s->ucred);
259
260 if (s->forward_to_console || s->manager->config.forward_to_console)
261 manager_forward_console(s->manager, priority, s->identifier, p, &s->ucred);
262
263 if (s->manager->config.forward_to_wall)
264 manager_forward_wall(s->manager, priority, s->identifier, p, &s->ucred);
265
266 m = N_IOVEC_META_FIELDS + 7 + client_context_extra_fields_n_iovec(s->context);
267 iovec = newa(struct iovec, m);
268
269 iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=stdout");
270 iovec[n++] = IOVEC_MAKE_STRING(s->id_field);
271
272 syslog_priority[STRLEN("PRIORITY=")] = '0' + LOG_PRI(priority);
273 iovec[n++] = IOVEC_MAKE_STRING(syslog_priority);
274
275 if (LOG_FAC(priority) != 0) {
276 xsprintf(syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority));
277 iovec[n++] = IOVEC_MAKE_STRING(syslog_facility);
278 }
279
280 if (s->identifier) {
281 syslog_identifier = strjoin("SYSLOG_IDENTIFIER=", s->identifier);
282 if (syslog_identifier)
283 iovec[n++] = IOVEC_MAKE_STRING(syslog_identifier);
284 }
285
286 static const char * const line_break_field_table[_LINE_BREAK_MAX] = {
287 [LINE_BREAK_NEWLINE] = NULL, /* Do not add field if traditional newline */
288 [LINE_BREAK_NUL] = "_LINE_BREAK=nul",
289 [LINE_BREAK_LINE_MAX] = "_LINE_BREAK=line-max",
290 [LINE_BREAK_EOF] = "_LINE_BREAK=eof",
291 [LINE_BREAK_PID_CHANGE] = "_LINE_BREAK=pid-change",
292 };
293
294 const char *c = line_break_field_table[line_break];
295
296 /* If this log message was generated due to an uncommon line break then mention this in the log
297 * entry */
298 if (c)
299 iovec[n++] = IOVEC_MAKE_STRING(c);
300
301 message = strjoin("MESSAGE=", p);
302 if (message)
303 iovec[n++] = IOVEC_MAKE_STRING(message);
304
305 manager_dispatch_message(s->manager, iovec, n, m, s->context, NULL, priority, 0);
306 return 0;
307 }
308
309 static int syslog_parse_priority_and_facility(const char *s) {
310 int prio, r;
311
312 /* Parses both facility and priority in one value, i.e. is different from log_level_from_string()
313 * which only parses the priority and refuses any facility value */
314
315 r = safe_atoi(s, &prio);
316 if (r < 0)
317 return r;
318
319 if (prio < 0 || prio > 999)
320 return -ERANGE;
321
322 return prio;
323 }
324
325 static int stdout_stream_line(StdoutStream *s, char *p, LineBreak line_break) {
326 char *orig;
327 int r;
328
329 assert(s);
330 assert(p);
331
332 orig = p;
333 p = strstrip(p);
334
335 /* line breaks by NUL, line max length or EOF are not permissible during the negotiation part of the protocol */
336 if (line_break != LINE_BREAK_NEWLINE && s->state != STDOUT_STREAM_RUNNING)
337 return log_ratelimit_warning_errno(SYNTHETIC_ERRNO(EINVAL), JOURNAL_LOG_RATELIMIT,
338 "Control protocol line not properly terminated.");
339
340 switch (s->state) {
341
342 case STDOUT_STREAM_IDENTIFIER:
343 if (!isempty(p)) {
344 s->identifier = strdup(p);
345 if (!s->identifier)
346 return log_oom();
347 }
348
349 s->state = STDOUT_STREAM_UNIT_ID;
350 return 0;
351
352 case STDOUT_STREAM_UNIT_ID:
353 if (s->ucred.uid == 0 &&
354 unit_name_is_valid(p, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
355
356 s->unit_id = strdup(p);
357 if (!s->unit_id)
358 return log_oom();
359 }
360
361 s->state = STDOUT_STREAM_PRIORITY;
362 return 0;
363
364 case STDOUT_STREAM_PRIORITY: {
365 int priority;
366
367 priority = syslog_parse_priority_and_facility(p);
368 if (priority < 0)
369 return log_ratelimit_warning_errno(priority, JOURNAL_LOG_RATELIMIT,
370 "Failed to parse log priority line: %m");
371
372 s->priority = priority;
373 s->state = STDOUT_STREAM_LEVEL_PREFIX;
374 return 0;
375 }
376
377 case STDOUT_STREAM_LEVEL_PREFIX:
378 r = parse_boolean(p);
379 if (r < 0)
380 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
381 "Failed to parse level prefix line: %m");
382
383 s->level_prefix = r;
384 s->state = STDOUT_STREAM_FORWARD_TO_SYSLOG;
385 return 0;
386
387 case STDOUT_STREAM_FORWARD_TO_SYSLOG:
388 r = parse_boolean(p);
389 if (r < 0)
390 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
391 "Failed to parse forward to syslog line: %m");
392
393 s->forward_to_syslog = r;
394 s->state = STDOUT_STREAM_FORWARD_TO_KMSG;
395 return 0;
396
397 case STDOUT_STREAM_FORWARD_TO_KMSG:
398 r = parse_boolean(p);
399 if (r < 0)
400 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
401 "Failed to parse copy to kmsg line: %m");
402
403 s->forward_to_kmsg = r;
404 s->state = STDOUT_STREAM_FORWARD_TO_CONSOLE;
405 return 0;
406
407 case STDOUT_STREAM_FORWARD_TO_CONSOLE:
408 r = parse_boolean(p);
409 if (r < 0)
410 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
411 "Failed to parse copy to console line.");
412
413 s->forward_to_console = r;
414 s->state = STDOUT_STREAM_RUNNING;
415
416 /* Try to save the stream, so that journald can be restarted and we can recover */
417 (void) stdout_stream_save(s);
418 return 0;
419
420 case STDOUT_STREAM_RUNNING:
421 return stdout_stream_log(s, orig, line_break);
422 }
423
424 assert_not_reached();
425 }
426
427 static int stdout_stream_found(
428 StdoutStream *s,
429 char *p,
430 size_t l,
431 LineBreak line_break) {
432
433 char saved;
434 int r;
435
436 assert(s);
437 assert(p);
438
439 /* Let's NUL terminate the specified buffer for this call, and revert back afterwards */
440 saved = p[l];
441 p[l] = 0;
442 r = stdout_stream_line(s, p, line_break);
443 p[l] = saved;
444
445 return r;
446 }
447
448 static size_t stdout_stream_line_max(StdoutStream *s) {
449 assert(s);
450
451 /* During the "setup" phase of our protocol, let's ensure we use a line length where a full unit name
452 * can fit in */
453 if (s->state != STDOUT_STREAM_RUNNING)
454 return STDOUT_STREAM_SETUP_PROTOCOL_LINE_MAX;
455
456 /* After the protocol's "setup" phase is complete, let's use whatever the user configured */
457 return s->manager->config.line_max;
458 }
459
460 static int stdout_stream_scan(
461 StdoutStream *s,
462 char *p,
463 size_t remaining,
464 LineBreak force_flush,
465 size_t *ret_consumed) {
466
467 size_t consumed = 0;
468 int r;
469
470 assert(s);
471 assert(p);
472
473 for (;;) {
474 LineBreak line_break;
475 size_t skip, found;
476 char *end1, *end2;
477 size_t tmp_remaining, line_max;
478
479 line_max = stdout_stream_line_max(s);
480 tmp_remaining = MIN(remaining, line_max);
481
482 end1 = memchr(p, '\n', tmp_remaining);
483 end2 = memchr(p, 0, end1 ? (size_t) (end1 - p) : tmp_remaining);
484
485 if (end2) {
486 /* We found a NUL terminator */
487 found = end2 - p;
488 skip = found + 1;
489 line_break = LINE_BREAK_NUL;
490 } else if (end1) {
491 /* We found a \n terminator */
492 found = end1 - p;
493 skip = found + 1;
494 line_break = LINE_BREAK_NEWLINE;
495 } else if (remaining >= line_max) {
496 /* Force a line break after the maximum line length */
497 found = skip = line_max;
498 line_break = LINE_BREAK_LINE_MAX;
499 } else
500 break;
501
502 r = stdout_stream_found(s, p, found, line_break);
503 if (r < 0)
504 return r;
505
506 p += skip;
507 consumed += skip;
508 remaining -= skip;
509 }
510
511 if (force_flush >= 0 && remaining > 0) {
512 r = stdout_stream_found(s, p, remaining, force_flush);
513 if (r < 0)
514 return r;
515
516 consumed += remaining;
517 }
518
519 if (ret_consumed)
520 *ret_consumed = consumed;
521
522 return 0;
523 }
524
525 static int stdout_stream_process(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
526 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
527 size_t limit, consumed, allocated;
528 StdoutStream *s = ASSERT_PTR(userdata);
529 struct ucred *ucred;
530 struct iovec iovec;
531 ssize_t l;
532 char *p;
533 int r;
534
535 struct msghdr msghdr = {
536 .msg_iov = &iovec,
537 .msg_iovlen = 1,
538 .msg_control = &control,
539 .msg_controllen = sizeof(control),
540 };
541
542 if ((revents|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
543 log_error("Got invalid event from epoll for stdout stream: %"PRIx32, revents);
544 goto terminate;
545 }
546
547 /* If the buffer is almost full, add room for another 1K */
548 allocated = MALLOC_ELEMENTSOF(s->buffer);
549 if (s->length + 512 >= allocated) {
550 if (!GREEDY_REALLOC(s->buffer, s->length + 1 + 1024)) {
551 log_oom();
552 goto terminate;
553 }
554
555 allocated = MALLOC_ELEMENTSOF(s->buffer);
556 }
557
558 /* Try to make use of the allocated buffer in full, but never read more than the configured line size. Also,
559 * always leave room for a terminating NUL we might need to add. */
560 /* Silence static analyzers, GREEDY_REALLOC above ensures allocated > 0 */
561 assert(allocated > 0);
562 limit = MIN(allocated - 1, MAX(s->manager->config.line_max, STDOUT_STREAM_SETUP_PROTOCOL_LINE_MAX));
563 assert(s->length <= limit);
564 iovec = IOVEC_MAKE(s->buffer + s->length, limit - s->length);
565
566 l = recvmsg(s->fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
567 if (l < 0) {
568 if (ERRNO_IS_TRANSIENT(errno))
569 return 0;
570
571 log_ratelimit_warning_errno(errno, JOURNAL_LOG_RATELIMIT, "Failed to read from stream: %m");
572 goto terminate;
573 }
574 cmsg_close_all(&msghdr);
575
576 if (l == 0) {
577 (void) stdout_stream_scan(s, s->buffer, s->length, /* force_flush= */ LINE_BREAK_EOF, NULL);
578 goto terminate;
579 }
580
581 /* Invalidate the context if the PID of the sender changed. This happens when a forked process
582 * inherits stdout/stderr from a parent. In this case getpeercred() returns the ucred of the parent,
583 * which can be invalid if the parent has exited in the meantime. */
584 ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
585 if (ucred && ucred->pid != s->ucred.pid) {
586 /* Force out any previously half-written lines from a different process, before we switch to
587 * the new ucred structure for everything we just added */
588 r = stdout_stream_scan(s, s->buffer, s->length, /* force_flush= */ LINE_BREAK_PID_CHANGE, NULL);
589 if (r < 0)
590 goto terminate;
591
592 s->context = client_context_release(s->manager, s->context);
593
594 p = s->buffer + s->length;
595 } else {
596 p = s->buffer;
597 l += s->length;
598 }
599
600 /* Always copy in the new credentials */
601 if (ucred)
602 s->ucred = *ucred;
603
604 r = stdout_stream_scan(s, p, l, _LINE_BREAK_INVALID, &consumed);
605 if (r < 0)
606 goto terminate;
607
608 /* Move what wasn't consumed to the front of the buffer */
609 assert(consumed <= (size_t) l);
610 s->length = l - consumed;
611 memmove(s->buffer, p + consumed, s->length);
612
613 LIST_FOREACH(by_stdout_stream, ssr, s->stream_sync_reqs)
614 /* NB: this might invalidate the stdout stream! */
615 stream_sync_req_advance_revalidate(ssr, consumed);
616
617 return 1;
618
619 terminate:
620 stdout_stream_terminate(s);
621 return 0;
622 }
623
624 int stdout_stream_install(Manager *m, int fd, StdoutStream **ret) {
625 _cleanup_(stdout_stream_freep) StdoutStream *stream = NULL;
626 sd_id128_t id;
627 int r;
628
629 assert(m);
630 assert(fd >= 0);
631
632 r = sd_id128_randomize(&id);
633 if (r < 0)
634 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to generate stream ID: %m");
635
636 stream = new(StdoutStream, 1);
637 if (!stream)
638 return log_oom();
639
640 *stream = (StdoutStream) {
641 .fd = -EBADF,
642 .priority = LOG_INFO,
643 .ucred = UCRED_INVALID,
644 };
645
646 xsprintf(stream->id_field, "_STREAM_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(id));
647
648 r = getpeercred(fd, &stream->ucred);
649 if (r < 0)
650 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to determine peer credentials: %m");
651
652 if (mac_selinux_use()) {
653 r = getpeersec(fd, &stream->label);
654 if (r < 0 && r != -EOPNOTSUPP)
655 (void) log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to determine peer security context: %m");
656 }
657
658 (void) shutdown(fd, SHUT_WR);
659
660 r = sd_event_add_io(m->event, &stream->event_source, fd, EPOLLIN, stdout_stream_process, stream);
661 if (r < 0)
662 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to add stream to event loop: %m");
663
664 r = sd_event_source_set_priority(stream->event_source, SD_EVENT_PRIORITY_NORMAL+5);
665 if (r < 0)
666 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to adjust stdout event source priority: %m");
667
668 stream->fd = fd;
669
670 stream->manager = m;
671 LIST_PREPEND(stdout_stream, m->stdout_streams, stream);
672 m->n_stdout_streams++;
673
674 (void) manager_start_or_stop_idle_timer(m); /* Maybe no longer idle? */
675
676 if (ret)
677 *ret = stream;
678
679 TAKE_PTR(stream);
680 return 0;
681 }
682
683 static int stdout_stream_new(sd_event_source *es, int listen_fd, uint32_t revents, void *userdata) {
684 _cleanup_close_ int fd = -EBADF;
685 Manager *m = ASSERT_PTR(userdata);
686 int r;
687
688 if (revents != EPOLLIN)
689 return log_error_errno(SYNTHETIC_ERRNO(EIO),
690 "Got invalid event from epoll for stdout server fd: %" PRIx32,
691 revents);
692
693 fd = accept4(m->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
694 if (fd < 0) {
695 if (ERRNO_IS_ACCEPT_AGAIN(errno))
696 return 0;
697
698 return log_ratelimit_error_errno(errno, JOURNAL_LOG_RATELIMIT, "Failed to accept stdout connection: %m");
699 }
700
701 if (m->n_stdout_streams >= STDOUT_STREAMS_MAX) {
702 struct ucred u = UCRED_INVALID;
703
704 (void) getpeercred(fd, &u);
705
706 /* By closing fd here we make sure that the client won't wait too long for journald to
707 * gather all the data it adds to the error message to find out that the connection has
708 * just been refused.
709 */
710 fd = safe_close(fd);
711
712 manager_driver_message(m, u.pid, LOG_MESSAGE("Too many stdout streams, refusing connection."));
713
714 manager_notify_stream(m, /* stream= */ NULL);
715 return 0;
716 }
717
718 StdoutStream *stream;
719 r = stdout_stream_install(m, fd, &stream);
720 if (r < 0) {
721 manager_notify_stream(m, /* stream= */ NULL);
722 return r;
723 }
724
725 TAKE_FD(fd);
726
727 /* Tell the synchronization logic that we dropped one item from the incoming connection queue */
728 manager_notify_stream(m, stream);
729
730 return 0;
731 }
732
733 static int stdout_stream_load(StdoutStream *stream, const char *fname) {
734 _cleanup_free_ char
735 *priority = NULL,
736 *level_prefix = NULL,
737 *forward_to_syslog = NULL,
738 *forward_to_kmsg = NULL,
739 *forward_to_console = NULL,
740 *stream_id = NULL;
741 int r;
742
743 assert(stream);
744 assert(fname);
745
746 if (!stream->state_file) {
747 stream->state_file = path_join(stream->manager->runtime_directory, "streams", fname);
748 if (!stream->state_file)
749 return log_oom();
750 }
751
752 r = parse_env_file(NULL, stream->state_file,
753 "PRIORITY", &priority,
754 "LEVEL_PREFIX", &level_prefix,
755 "FORWARD_TO_SYSLOG", &forward_to_syslog,
756 "FORWARD_TO_KMSG", &forward_to_kmsg,
757 "FORWARD_TO_CONSOLE", &forward_to_console,
758 "IDENTIFIER", &stream->identifier,
759 "UNIT", &stream->unit_id,
760 "STREAM_ID", &stream_id);
761 if (r < 0)
762 return log_error_errno(r, "Failed to read: %s", stream->state_file);
763
764 if (priority) {
765 int p;
766
767 p = syslog_parse_priority_and_facility(priority);
768 if (p >= 0)
769 stream->priority = p;
770 }
771
772 if (level_prefix) {
773 r = parse_boolean(level_prefix);
774 if (r >= 0)
775 stream->level_prefix = r;
776 }
777
778 if (forward_to_syslog) {
779 r = parse_boolean(forward_to_syslog);
780 if (r >= 0)
781 stream->forward_to_syslog = r;
782 }
783
784 if (forward_to_kmsg) {
785 r = parse_boolean(forward_to_kmsg);
786 if (r >= 0)
787 stream->forward_to_kmsg = r;
788 }
789
790 if (forward_to_console) {
791 r = parse_boolean(forward_to_console);
792 if (r >= 0)
793 stream->forward_to_console = r;
794 }
795
796 if (stream_id) {
797 sd_id128_t id;
798
799 r = sd_id128_from_string(stream_id, &id);
800 if (r >= 0)
801 xsprintf(stream->id_field, "_STREAM_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(id));
802 }
803
804 return 0;
805 }
806
807 static int stdout_stream_restore(Manager *m, const char *fname, int fd) {
808 StdoutStream *stream;
809 int r;
810
811 assert(m);
812 assert(fname);
813 assert(fd >= 0);
814
815 if (m->n_stdout_streams >= STDOUT_STREAMS_MAX)
816 return log_warning_errno(SYNTHETIC_ERRNO(ENOBUFS),
817 "Too many stdout streams, refusing restoring of stream.");
818
819 r = stdout_stream_install(m, fd, &stream);
820 if (r < 0)
821 return r;
822
823 stream->state = STDOUT_STREAM_RUNNING;
824 stream->fdstore = true;
825
826 /* Ignore all parsing errors */
827 (void) stdout_stream_load(stream, fname);
828
829 return 0;
830 }
831
832 int manager_restore_streams(Manager *m, FDSet *fds) {
833 _cleanup_closedir_ DIR *d = NULL;
834 const char *path;
835 int r;
836
837 path = strjoina(m->runtime_directory, "/streams");
838 d = opendir(path);
839 if (!d) {
840 if (errno == ENOENT)
841 return 0;
842
843 return log_warning_errno(errno, "Failed to enumerate %s: %m", path);
844 }
845
846 FOREACH_DIRENT(de, d, goto fail) {
847 unsigned long st_dev, st_ino;
848 bool found = false;
849 int fd;
850
851 if (sscanf(de->d_name, "%lu:%lu", &st_dev, &st_ino) != 2)
852 continue;
853
854 FDSET_FOREACH(fd, fds) {
855 struct stat st;
856
857 if (fstat(fd, &st) < 0)
858 return log_error_errno(errno, "Failed to stat %s: %m", de->d_name);
859
860 if (S_ISSOCK(st.st_mode) && st.st_dev == st_dev && st.st_ino == st_ino) {
861 found = true;
862 break;
863 }
864 }
865
866 if (!found) {
867 /* No file descriptor? Then let's delete the state file */
868 log_debug("Cannot restore stream file %s", de->d_name);
869 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
870 log_warning_errno(errno, "Failed to remove %s/%s: %m", path, de->d_name);
871 continue;
872 }
873
874 fdset_remove(fds, fd);
875
876 r = stdout_stream_restore(m, de->d_name, fd);
877 if (r < 0)
878 safe_close(fd);
879 }
880
881 return 0;
882
883 fail:
884 return log_error_errno(errno, "Failed to read streams directory: %m");
885 }
886
887 int manager_open_stdout_socket(Manager *m, const char *stdout_socket) {
888 int r;
889
890 assert(m);
891 assert(stdout_socket);
892
893 if (m->stdout_fd < 0) {
894 union sockaddr_union sa;
895 socklen_t sa_len;
896
897 r = sockaddr_un_set_path(&sa.un, stdout_socket);
898 if (r < 0)
899 return log_error_errno(r, "Unable to use namespace path %s for AF_UNIX socket: %m", stdout_socket);
900 sa_len = r;
901
902 m->stdout_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
903 if (m->stdout_fd < 0)
904 return log_error_errno(errno, "socket() failed: %m");
905
906 (void) sockaddr_un_unlink(&sa.un);
907
908 r = bind(m->stdout_fd, &sa.sa, sa_len);
909 if (r < 0)
910 return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
911
912 (void) chmod(sa.un.sun_path, 0666);
913
914 if (listen(m->stdout_fd, SOMAXCONN_DELUXE) < 0)
915 return log_error_errno(errno, "listen(%s) failed: %m", sa.un.sun_path);
916 } else
917 (void) fd_nonblock(m->stdout_fd, true);
918
919 r = setsockopt_int(m->stdout_fd, SOL_SOCKET, SO_PASSCRED, true);
920 if (r < 0)
921 return log_error_errno(r, "Failed to enable SO_PASSCRED: %m");
922
923 r = setsockopt_int(m->stdout_fd, SOL_SOCKET, SO_PASSRIGHTS, false);
924 if (r < 0)
925 log_debug_errno(r, "Failed to turn off SO_PASSRIGHTS, ignoring: %m");
926
927 r = sd_event_add_io(m->event, &m->stdout_event_source, m->stdout_fd, EPOLLIN, stdout_stream_new, m);
928 if (r < 0)
929 return log_error_errno(r, "Failed to add stdout server fd to event source: %m");
930
931 r = sd_event_source_set_priority(m->stdout_event_source, SD_EVENT_PRIORITY_NORMAL+5);
932 if (r < 0)
933 return log_error_errno(r, "Failed to adjust priority of stdout server event source: %m");
934
935 return 0;
936 }
937
938 void stdout_stream_send_notify(StdoutStream *s) {
939 struct iovec iovec = {
940 .iov_base = (char*) "FDSTORE=1",
941 .iov_len = STRLEN("FDSTORE=1"),
942 };
943 struct msghdr msghdr = {
944 .msg_iov = &iovec,
945 .msg_iovlen = 1,
946 };
947 struct cmsghdr *cmsg;
948 ssize_t l;
949
950 assert(s);
951 assert(!s->fdstore);
952 assert(s->in_notify_queue);
953 assert(s->manager);
954 assert(s->manager->notify_fd >= 0);
955
956 /* Store the connection fd in PID 1, so that we get it passed
957 * in again on next start */
958
959 msghdr.msg_controllen = CMSG_SPACE(sizeof(int));
960 msghdr.msg_control = alloca0(msghdr.msg_controllen);
961
962 cmsg = CMSG_FIRSTHDR(&msghdr);
963 cmsg->cmsg_level = SOL_SOCKET;
964 cmsg->cmsg_type = SCM_RIGHTS;
965 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
966
967 memcpy(CMSG_DATA(cmsg), &s->fd, sizeof(int));
968
969 l = sendmsg(s->manager->notify_fd, &msghdr, MSG_DONTWAIT|MSG_NOSIGNAL);
970 if (l < 0) {
971 if (errno == EAGAIN)
972 return;
973
974 log_error_errno(errno, "Failed to send stream file descriptor to service manager: %m");
975 } else {
976 log_debug("Successfully sent stream file descriptor to service manager.");
977 s->fdstore = 1;
978 }
979
980 LIST_REMOVE(stdout_stream_notify_queue, s->manager->stdout_streams_notify_queue, s);
981 s->in_notify_queue = false;
982 }