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