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