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