]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-bus/bus-socket.c
Merge pull request #27563 from yuwata/fstab-generator
[thirdparty/systemd.git] / src / libsystemd / sd-bus / bus-socket.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <endian.h>
4 #include <poll.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7
8 #include "sd-bus.h"
9 #include "sd-daemon.h"
10
11 #include "alloc-util.h"
12 #include "bus-internal.h"
13 #include "bus-message.h"
14 #include "bus-socket.h"
15 #include "escape.h"
16 #include "fd-util.h"
17 #include "format-util.h"
18 #include "fs-util.h"
19 #include "hexdecoct.h"
20 #include "io-util.h"
21 #include "macro.h"
22 #include "memory-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "random-util.h"
26 #include "signal-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "user-util.h"
30 #include "utf8.h"
31
32 #define SNDBUF_SIZE (8*1024*1024)
33
34 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
35
36 while (size > 0) {
37 struct iovec *i = iov + *idx;
38
39 if (i->iov_len > size) {
40 i->iov_base = (uint8_t*) i->iov_base + size;
41 i->iov_len -= size;
42 return;
43 }
44
45 size -= i->iov_len;
46
47 *i = IOVEC_MAKE(NULL, 0);
48
49 (*idx)++;
50 }
51 }
52
53 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
54 assert(m);
55 assert(p);
56 assert(sz > 0);
57
58 m->iovec[m->n_iovec++] = IOVEC_MAKE((void*) p, sz);
59
60 return 0;
61 }
62
63 static int bus_message_setup_iovec(sd_bus_message *m) {
64 struct bus_body_part *part;
65 unsigned n, i;
66 int r;
67
68 assert(m);
69 assert(m->sealed);
70
71 if (m->n_iovec > 0)
72 return 0;
73
74 assert(!m->iovec);
75
76 n = 1 + m->n_body_parts;
77 if (n < ELEMENTSOF(m->iovec_fixed))
78 m->iovec = m->iovec_fixed;
79 else {
80 m->iovec = new(struct iovec, n);
81 if (!m->iovec) {
82 r = -ENOMEM;
83 goto fail;
84 }
85 }
86
87 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
88 if (r < 0)
89 goto fail;
90
91 MESSAGE_FOREACH_PART(part, i, m) {
92 r = bus_body_part_map(part);
93 if (r < 0)
94 goto fail;
95
96 r = append_iovec(m, part->data, part->size);
97 if (r < 0)
98 goto fail;
99 }
100
101 assert(n == m->n_iovec);
102
103 return 0;
104
105 fail:
106 m->poisoned = true;
107 return r;
108 }
109
110 bool bus_socket_auth_needs_write(sd_bus *b) {
111
112 unsigned i;
113
114 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
115 return false;
116
117 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
118 struct iovec *j = b->auth_iovec + i;
119
120 if (j->iov_len > 0)
121 return true;
122 }
123
124 return false;
125 }
126
127 static int bus_socket_auth_verify_client(sd_bus *b) {
128 char *l, *lines[4] = {};
129 sd_id128_t peer;
130 size_t i, n;
131 int r;
132
133 assert(b);
134
135 /*
136 * We expect up to three response lines:
137 * "DATA\r\n" (optional)
138 * "OK <server-id>\r\n"
139 * "AGREE_UNIX_FD\r\n" (optional)
140 */
141
142 n = 0;
143 lines[n] = b->rbuffer;
144 for (i = 0; i < 3; ++i) {
145 l = memmem_safe(lines[n], b->rbuffer_size - (lines[n] - (char*) b->rbuffer), "\r\n", 2);
146 if (l)
147 lines[++n] = l + 2;
148 else
149 break;
150 }
151
152 /*
153 * If we sent a non-empty initial response, then we just expect an OK
154 * reply. We currently do this if, and only if, we picked ANONYMOUS.
155 * If we did not send an initial response, then we expect a DATA
156 * challenge, reply with our own DATA, and expect an OK reply. We do
157 * this for EXTERNAL.
158 * If FD negotiation was requested, we additionally expect
159 * an AGREE_UNIX_FD response in all cases.
160 */
161 if (n < (b->anonymous_auth ? 1U : 2U) + !!b->accept_fd)
162 return 0; /* wait for more data */
163
164 i = 0;
165
166 /* In case of EXTERNAL, verify the first response was DATA. */
167 if (!b->anonymous_auth) {
168 l = lines[i++];
169 if (lines[i] - l == 4 + 2) {
170 if (memcmp(l, "DATA", 4))
171 return -EPERM;
172 } else if (lines[i] - l == 3 + 32 + 2) {
173 /*
174 * Old versions of the server-side implementation of
175 * `sd-bus` replied with "OK <id>" to "AUTH" requests
176 * from a client, even if the "AUTH" line did not
177 * contain inlined arguments. Therefore, we also accept
178 * "OK <id>" here, even though it is technically the
179 * wrong reply. We ignore the "<id>" parameter, though,
180 * since it has no real value.
181 */
182 if (memcmp(l, "OK ", 3))
183 return -EPERM;
184 } else
185 return -EPERM;
186 }
187
188 /* Now check the OK line. */
189 l = lines[i++];
190
191 if (lines[i] - l != 3 + 32 + 2)
192 return -EPERM;
193 if (memcmp(l, "OK ", 3))
194 return -EPERM;
195
196 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
197
198 for (unsigned j = 0; j < 32; j += 2) {
199 int x, y;
200
201 x = unhexchar(l[3 + j]);
202 y = unhexchar(l[3 + j + 1]);
203
204 if (x < 0 || y < 0)
205 return -EINVAL;
206
207 peer.bytes[j/2] = ((uint8_t) x << 4 | (uint8_t) y);
208 }
209
210 if (!sd_id128_is_null(b->server_id) &&
211 !sd_id128_equal(b->server_id, peer))
212 return -EPERM;
213
214 b->server_id = peer;
215
216 /* And possibly check the third line, too */
217 if (b->accept_fd) {
218 l = lines[i++];
219 b->can_fds = !!memory_startswith(l, lines[i] - l, "AGREE_UNIX_FD");
220 }
221
222 assert(i == n);
223
224 b->rbuffer_size -= (lines[i] - (char*) b->rbuffer);
225 memmove(b->rbuffer, lines[i], b->rbuffer_size);
226
227 r = bus_start_running(b);
228 if (r < 0)
229 return r;
230
231 return 1;
232 }
233
234 static bool line_equals(const char *s, size_t m, const char *line) {
235 size_t l;
236
237 l = strlen(line);
238 if (l != m)
239 return false;
240
241 return memcmp(s, line, l) == 0;
242 }
243
244 static bool line_begins(const char *s, size_t m, const char *word) {
245 const char *p;
246
247 p = memory_startswith(s, m, word);
248 return p && (p == (s + m) || *p == ' ');
249 }
250
251 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
252 _cleanup_free_ char *token = NULL;
253 size_t len;
254 int r;
255
256 if (!b->anonymous_auth)
257 return 0;
258
259 if (l <= 0)
260 return 1;
261
262 assert(p[0] == ' ');
263 p++; l--;
264
265 if (l % 2 != 0)
266 return 0;
267
268 r = unhexmem(p, l, (void **) &token, &len);
269 if (r < 0)
270 return 0;
271
272 if (memchr(token, 0, len))
273 return 0;
274
275 return !!utf8_is_valid(token);
276 }
277
278 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
279 _cleanup_free_ char *token = NULL;
280 size_t len;
281 uid_t u;
282 int r;
283
284 /* We don't do any real authentication here. Instead, if
285 * the owner of this bus wanted authentication they should have
286 * checked SO_PEERCRED before even creating the bus object. */
287
288 if (!b->anonymous_auth && !b->ucred_valid)
289 return 0;
290
291 if (l <= 0)
292 return 1;
293
294 assert(p[0] == ' ');
295 p++; l--;
296
297 if (l % 2 != 0)
298 return 0;
299
300 r = unhexmem(p, l, (void**) &token, &len);
301 if (r < 0)
302 return 0;
303
304 if (memchr(token, 0, len))
305 return 0;
306
307 r = parse_uid(token, &u);
308 if (r < 0)
309 return 0;
310
311 /* We ignore the passed value if anonymous authentication is
312 * on anyway. */
313 if (!b->anonymous_auth && u != b->ucred.uid)
314 return 0;
315
316 return 1;
317 }
318
319 static int bus_socket_auth_write(sd_bus *b, const char *t) {
320 char *p;
321 size_t l;
322
323 assert(b);
324 assert(t);
325
326 /* We only make use of the first iovec */
327 assert(IN_SET(b->auth_index, 0, 1));
328
329 l = strlen(t);
330 p = malloc(b->auth_iovec[0].iov_len + l);
331 if (!p)
332 return -ENOMEM;
333
334 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
335 memcpy(p + b->auth_iovec[0].iov_len, t, l);
336
337 b->auth_iovec[0].iov_base = p;
338 b->auth_iovec[0].iov_len += l;
339
340 free_and_replace(b->auth_buffer, p);
341 b->auth_index = 0;
342 return 0;
343 }
344
345 static int bus_socket_auth_write_ok(sd_bus *b) {
346 char t[3 + 32 + 2 + 1];
347
348 assert(b);
349
350 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
351
352 return bus_socket_auth_write(b, t);
353 }
354
355 static int bus_socket_auth_verify_server(sd_bus *b) {
356 char *e;
357 const char *line;
358 size_t l;
359 bool processed = false;
360 int r;
361
362 assert(b);
363
364 if (b->rbuffer_size < 1)
365 return 0;
366
367 /* First char must be a NUL byte */
368 if (*(char*) b->rbuffer != 0)
369 return -EIO;
370
371 if (b->rbuffer_size < 3)
372 return 0;
373
374 /* Begin with the first line */
375 if (b->auth_rbegin <= 0)
376 b->auth_rbegin = 1;
377
378 for (;;) {
379 /* Check if line is complete */
380 line = (char*) b->rbuffer + b->auth_rbegin;
381 e = memmem_safe(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
382 if (!e)
383 return processed;
384
385 l = e - line;
386
387 if (line_begins(line, l, "AUTH ANONYMOUS")) {
388
389 r = verify_anonymous_token(b,
390 line + strlen("AUTH ANONYMOUS"),
391 l - strlen("AUTH ANONYMOUS"));
392 if (r < 0)
393 return r;
394 if (r == 0)
395 r = bus_socket_auth_write(b, "REJECTED\r\n");
396 else {
397 b->auth = BUS_AUTH_ANONYMOUS;
398 if (l <= strlen("AUTH ANONYMOUS"))
399 r = bus_socket_auth_write(b, "DATA\r\n");
400 else
401 r = bus_socket_auth_write_ok(b);
402 }
403
404 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
405
406 r = verify_external_token(b,
407 line + strlen("AUTH EXTERNAL"),
408 l - strlen("AUTH EXTERNAL"));
409 if (r < 0)
410 return r;
411 if (r == 0)
412 r = bus_socket_auth_write(b, "REJECTED\r\n");
413 else {
414 b->auth = BUS_AUTH_EXTERNAL;
415 if (l <= strlen("AUTH EXTERNAL"))
416 r = bus_socket_auth_write(b, "DATA\r\n");
417 else
418 r = bus_socket_auth_write_ok(b);
419 }
420
421 } else if (line_begins(line, l, "AUTH"))
422 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
423 else if (line_equals(line, l, "CANCEL") ||
424 line_begins(line, l, "ERROR")) {
425
426 b->auth = _BUS_AUTH_INVALID;
427 r = bus_socket_auth_write(b, "REJECTED\r\n");
428
429 } else if (line_equals(line, l, "BEGIN")) {
430
431 if (b->auth == _BUS_AUTH_INVALID)
432 r = bus_socket_auth_write(b, "ERROR\r\n");
433 else {
434 /* We can't leave from the auth phase
435 * before we haven't written
436 * everything queued, so let's check
437 * that */
438
439 if (bus_socket_auth_needs_write(b))
440 return 1;
441
442 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
443 memmove(b->rbuffer, e + 2, b->rbuffer_size);
444 return bus_start_running(b);
445 }
446
447 } else if (line_begins(line, l, "DATA")) {
448
449 if (b->auth == _BUS_AUTH_INVALID)
450 r = bus_socket_auth_write(b, "ERROR\r\n");
451 else {
452 if (b->auth == BUS_AUTH_ANONYMOUS)
453 r = verify_anonymous_token(b, line + 4, l - 4);
454 else
455 r = verify_external_token(b, line + 4, l - 4);
456
457 if (r < 0)
458 return r;
459 if (r == 0) {
460 b->auth = _BUS_AUTH_INVALID;
461 r = bus_socket_auth_write(b, "REJECTED\r\n");
462 } else
463 r = bus_socket_auth_write_ok(b);
464 }
465 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
466 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
467 r = bus_socket_auth_write(b, "ERROR\r\n");
468 else {
469 b->can_fds = true;
470 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
471 }
472 } else
473 r = bus_socket_auth_write(b, "ERROR\r\n");
474
475 if (r < 0)
476 return r;
477
478 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
479
480 processed = true;
481 }
482 }
483
484 static int bus_socket_auth_verify(sd_bus *b) {
485 assert(b);
486
487 if (b->is_server)
488 return bus_socket_auth_verify_server(b);
489 else
490 return bus_socket_auth_verify_client(b);
491 }
492
493 static int bus_socket_write_auth(sd_bus *b) {
494 ssize_t k;
495
496 assert(b);
497 assert(b->state == BUS_AUTHENTICATING);
498
499 if (!bus_socket_auth_needs_write(b))
500 return 0;
501
502 if (b->prefer_writev)
503 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
504 else {
505 struct msghdr mh = {
506 .msg_iov = b->auth_iovec + b->auth_index,
507 .msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index,
508 };
509
510 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
511 if (k < 0 && errno == ENOTSOCK) {
512 b->prefer_writev = true;
513 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
514 }
515 }
516
517 if (k < 0)
518 return ERRNO_IS_TRANSIENT(errno) ? 0 : -errno;
519
520 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
521
522 /* Now crank the state machine since we might be able to make progress after writing. For example,
523 * the server only processes "BEGIN" when the write buffer is empty.
524 */
525 return bus_socket_auth_verify(b);
526 }
527
528 static int bus_socket_read_auth(sd_bus *b) {
529 struct msghdr mh;
530 struct iovec iov = {};
531 size_t n;
532 ssize_t k;
533 int r;
534 void *p;
535 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
536 bool handle_cmsg = false;
537
538 assert(b);
539 assert(b->state == BUS_AUTHENTICATING);
540
541 r = bus_socket_auth_verify(b);
542 if (r != 0)
543 return r;
544
545 n = MAX(256u, b->rbuffer_size * 2);
546
547 if (n > BUS_AUTH_SIZE_MAX)
548 n = BUS_AUTH_SIZE_MAX;
549
550 if (b->rbuffer_size >= n)
551 return -ENOBUFS;
552
553 p = realloc(b->rbuffer, n);
554 if (!p)
555 return -ENOMEM;
556
557 b->rbuffer = p;
558
559 iov = IOVEC_MAKE((uint8_t *)b->rbuffer + b->rbuffer_size, n - b->rbuffer_size);
560
561 if (b->prefer_readv) {
562 k = readv(b->input_fd, &iov, 1);
563 if (k < 0)
564 k = -errno;
565 } else {
566 mh = (struct msghdr) {
567 .msg_iov = &iov,
568 .msg_iovlen = 1,
569 .msg_control = &control,
570 .msg_controllen = sizeof(control),
571 };
572
573 k = recvmsg_safe(b->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
574 if (k == -ENOTSOCK) {
575 b->prefer_readv = true;
576 k = readv(b->input_fd, &iov, 1);
577 if (k < 0)
578 k = -errno;
579 } else
580 handle_cmsg = true;
581 }
582 if (k < 0) {
583 if (ERRNO_IS_TRANSIENT(k))
584 return 0;
585 return (int) k;
586 }
587 if (k == 0) {
588 if (handle_cmsg)
589 cmsg_close_all(&mh); /* paranoia, we shouldn't have gotten any fds on EOF */
590 return -ECONNRESET;
591 }
592
593 b->rbuffer_size += k;
594
595 if (handle_cmsg) {
596 struct cmsghdr *cmsg;
597
598 CMSG_FOREACH(cmsg, &mh)
599 if (cmsg->cmsg_level == SOL_SOCKET &&
600 cmsg->cmsg_type == SCM_RIGHTS) {
601 int j;
602
603 /* Whut? We received fds during the auth
604 * protocol? Somebody is playing games with
605 * us. Close them all, and fail */
606 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
607 close_many(CMSG_TYPED_DATA(cmsg, int), j);
608 return -EIO;
609 } else
610 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
611 cmsg->cmsg_level, cmsg->cmsg_type);
612 }
613
614 r = bus_socket_auth_verify(b);
615 if (r != 0)
616 return r;
617
618 return 1;
619 }
620
621 void bus_socket_setup(sd_bus *b) {
622 assert(b);
623
624 /* Increase the buffers to 8 MB */
625 (void) fd_increase_rxbuf(b->input_fd, SNDBUF_SIZE);
626 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
627
628 b->message_version = 1;
629 b->message_endian = 0;
630 }
631
632 static void bus_get_peercred(sd_bus *b) {
633 int r;
634
635 assert(b);
636 assert(!b->ucred_valid);
637 assert(!b->label);
638 assert(b->n_groups == SIZE_MAX);
639
640 /* Get the peer for socketpair() sockets */
641 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
642
643 /* Get the SELinux context of the peer */
644 r = getpeersec(b->input_fd, &b->label);
645 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
646 log_debug_errno(r, "Failed to determine peer security context: %m");
647
648 /* Get the list of auxiliary groups of the peer */
649 r = getpeergroups(b->input_fd, &b->groups);
650 if (r >= 0)
651 b->n_groups = (size_t) r;
652 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
653 log_debug_errno(r, "Failed to determine peer's group list: %m");
654
655 /* Let's query the peers socket address, it might carry information such as the peer's comm or
656 * description string */
657 zero(b->sockaddr_peer);
658 b->sockaddr_size_peer = 0;
659
660 socklen_t l = sizeof(b->sockaddr_peer) - 1; /* Leave space for a NUL */
661 if (getpeername(b->input_fd, &b->sockaddr_peer.sa, &l) < 0)
662 log_debug_errno(errno, "Failed to get peer's socket address, ignoring: %m");
663 else
664 b->sockaddr_size_peer = l;
665 }
666
667 static int bus_socket_start_auth_client(sd_bus *b) {
668 static const char sasl_auth_anonymous[] = {
669 /*
670 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
671 * message broker to aid debugging of clients. We fully anonymize the connection and use a
672 * static default.
673 */
674 /* HEX a n o n y m o u s */
675 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
676 };
677 static const char sasl_auth_external[] = {
678 "\0AUTH EXTERNAL\r\n"
679 "DATA\r\n"
680 };
681 static const char sasl_negotiate_unix_fd[] = {
682 "NEGOTIATE_UNIX_FD\r\n"
683 };
684 static const char sasl_begin[] = {
685 "BEGIN\r\n"
686 };
687 size_t i = 0;
688
689 assert(b);
690
691 if (b->anonymous_auth)
692 b->auth_iovec[i++] = IOVEC_MAKE((char*) sasl_auth_anonymous, sizeof(sasl_auth_anonymous) - 1);
693 else
694 b->auth_iovec[i++] = IOVEC_MAKE((char*) sasl_auth_external, sizeof(sasl_auth_external) - 1);
695
696 if (b->accept_fd)
697 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd);
698
699 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_begin);
700
701 return bus_socket_write_auth(b);
702 }
703
704 int bus_socket_start_auth(sd_bus *b) {
705 assert(b);
706
707 bus_get_peercred(b);
708
709 bus_set_state(b, BUS_AUTHENTICATING);
710 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
711
712 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
713 b->accept_fd = false;
714
715 if (b->output_fd != b->input_fd)
716 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
717 b->accept_fd = false;
718
719 if (b->is_server)
720 return bus_socket_read_auth(b);
721 else
722 return bus_socket_start_auth_client(b);
723 }
724
725 static int bus_socket_inotify_setup(sd_bus *b) {
726 _cleanup_free_ int *new_watches = NULL;
727 _cleanup_free_ char *absolute = NULL;
728 size_t n = 0, done = 0, i;
729 unsigned max_follow = 32;
730 const char *p;
731 int wd, r;
732
733 assert(b);
734 assert(b->watch_bind);
735 assert(b->sockaddr.sa.sa_family == AF_UNIX);
736 assert(b->sockaddr.un.sun_path[0] != 0);
737
738 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
739 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
740 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
741 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
742 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
743 * components. */
744
745 if (b->inotify_fd < 0) {
746 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
747 if (b->inotify_fd < 0)
748 return -errno;
749
750 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
751 }
752
753 /* Make sure the path is NUL terminated */
754 p = strndupa_safe(b->sockaddr.un.sun_path,
755 sizeof(b->sockaddr.un.sun_path));
756
757 /* Make sure the path is absolute */
758 r = path_make_absolute_cwd(p, &absolute);
759 if (r < 0)
760 goto fail;
761
762 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
763 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
764 * they are removed or renamed. */
765
766 if (!GREEDY_REALLOC(new_watches, n + 1)) {
767 r = -ENOMEM;
768 goto fail;
769 }
770
771 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
772 * always exists */
773 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
774 if (wd < 0) {
775 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
776 goto fail;
777 } else
778 new_watches[n++] = wd;
779
780 for (;;) {
781 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
782 size_t n_slashes, n_component;
783 char *c = NULL;
784
785 n_slashes = strspn(absolute + done, "/");
786 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
787
788 if (n_component == 0) /* The end */
789 break;
790
791 component = strndup(absolute + done, n_component);
792 if (!component) {
793 r = -ENOMEM;
794 goto fail;
795 }
796
797 /* A trailing slash? That's a directory, and not a socket then */
798 if (path_equal(component, "/")) {
799 r = -EISDIR;
800 goto fail;
801 }
802
803 /* A single dot? Let's eat this up */
804 if (path_equal(component, "/.")) {
805 done += n_component;
806 continue;
807 }
808
809 prefix = strndup(absolute, done + n_component);
810 if (!prefix) {
811 r = -ENOMEM;
812 goto fail;
813 }
814
815 if (!GREEDY_REALLOC(new_watches, n + 1)) {
816 r = -ENOMEM;
817 goto fail;
818 }
819
820 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
821 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
822
823 if (wd < 0) {
824 if (IN_SET(errno, ENOENT, ELOOP))
825 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
826
827 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
828 goto fail;
829 } else
830 new_watches[n++] = wd;
831
832 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
833 r = readlink_malloc(prefix, &destination);
834 if (r == -EINVAL) { /* not a symlink */
835 done += n_component;
836 continue;
837 }
838 if (r < 0)
839 goto fail;
840
841 if (isempty(destination)) { /* Empty symlink target? Yuck! */
842 r = -EINVAL;
843 goto fail;
844 }
845
846 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
847 r = -ELOOP;
848 goto fail;
849 }
850
851 if (path_is_absolute(destination)) {
852 /* For absolute symlinks we build the new path and start anew */
853 c = strjoin(destination, absolute + done + n_component);
854 done = 0;
855 } else {
856 _cleanup_free_ char *t = NULL;
857
858 /* For relative symlinks we replace the last component, and try again */
859 t = strndup(absolute, done);
860 if (!t)
861 return -ENOMEM;
862
863 c = strjoin(t, "/", destination, absolute + done + n_component);
864 }
865 if (!c) {
866 r = -ENOMEM;
867 goto fail;
868 }
869
870 free_and_replace(absolute, c);
871
872 max_follow--;
873 }
874
875 /* And now, let's remove all watches from the previous iteration we don't need anymore */
876 for (i = 0; i < b->n_inotify_watches; i++) {
877 bool found = false;
878 size_t j;
879
880 for (j = 0; j < n; j++)
881 if (new_watches[j] == b->inotify_watches[i]) {
882 found = true;
883 break;
884 }
885
886 if (found)
887 continue;
888
889 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
890 }
891
892 free_and_replace(b->inotify_watches, new_watches);
893 b->n_inotify_watches = n;
894
895 return 0;
896
897 fail:
898 bus_close_inotify_fd(b);
899 return r;
900 }
901
902 static int bind_description(sd_bus *b, int fd, int family) {
903 _cleanup_free_ char *bind_name = NULL, *comm = NULL;
904 union sockaddr_union bsa;
905 const char *d = NULL;
906 int r;
907
908 assert(b);
909 assert(fd >= 0);
910
911 /* If this is an AF_UNIX socket, let's set our client's socket address to carry the description
912 * string for this bus connection. This is useful for debugging things, as the connection name is
913 * visible in various socket-related tools, and can even be queried by the server side. */
914
915 if (family != AF_UNIX)
916 return 0;
917
918 (void) sd_bus_get_description(b, &d);
919
920 /* Generate a recognizable source address in the abstract namespace. We'll include:
921 * - a random 64bit value (to avoid collisions)
922 * - our "comm" process name (suppressed if contains "/" to avoid parsing issues)
923 * - the description string of the bus connection. */
924 (void) get_process_comm(0, &comm);
925 if (comm && strchr(comm, '/'))
926 comm = mfree(comm);
927
928 if (!d && !comm) /* skip if we don't have either field, rely on kernel autobind instead */
929 return 0;
930
931 if (asprintf(&bind_name, "@%" PRIx64 "/bus/%s/%s", random_u64(), strempty(comm), strempty(d)) < 0)
932 return -ENOMEM;
933
934 strshorten(bind_name, sizeof_field(struct sockaddr_un, sun_path));
935
936 r = sockaddr_un_set_path(&bsa.un, bind_name);
937 if (r < 0)
938 return r;
939
940 if (bind(fd, &bsa.sa, r) < 0)
941 return -errno;
942
943 return 0;
944 }
945
946 int bus_socket_connect(sd_bus *b) {
947 bool inotify_done = false;
948 int r;
949
950 assert(b);
951
952 for (;;) {
953 assert(b->input_fd < 0);
954 assert(b->output_fd < 0);
955 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
956
957 if (DEBUG_LOGGING) {
958 _cleanup_free_ char *pretty = NULL;
959 (void) sockaddr_pretty(&b->sockaddr.sa, b->sockaddr_size, false, true, &pretty);
960 log_debug("sd-bus: starting bus%s%s by connecting to %s...",
961 b->description ? " " : "", strempty(b->description), strnull(pretty));
962 }
963
964 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
965 if (b->input_fd < 0)
966 return -errno;
967
968 r = bind_description(b, b->input_fd, b->sockaddr.sa.sa_family);
969 if (r < 0)
970 return r;
971
972 b->input_fd = fd_move_above_stdio(b->input_fd);
973
974 b->output_fd = b->input_fd;
975 bus_socket_setup(b);
976
977 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
978 if (errno == EINPROGRESS) {
979
980 /* If we have any inotify watches open, close them now, we don't need them anymore, as
981 * we have successfully initiated a connection */
982 bus_close_inotify_fd(b);
983
984 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
985 * we start parsing the address string. The only reason we set the state explicitly
986 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
987 bus_set_state(b, BUS_OPENING);
988 return 1;
989 }
990
991 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
992 b->watch_bind &&
993 b->sockaddr.sa.sa_family == AF_UNIX &&
994 b->sockaddr.un.sun_path[0] != 0) {
995
996 /* This connection attempt failed, let's release the socket for now, and start with a
997 * fresh one when reconnecting. */
998 bus_close_io_fds(b);
999
1000 if (inotify_done) {
1001 /* inotify set up already, don't do it again, just return now, and remember
1002 * that we are waiting for inotify events now. */
1003 bus_set_state(b, BUS_WATCH_BIND);
1004 return 1;
1005 }
1006
1007 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
1008 r = bus_socket_inotify_setup(b);
1009 if (r < 0)
1010 return r;
1011
1012 /* Let's now try to connect a second time, because in theory there's otherwise a race
1013 * here: the socket might have been created in the time between our first connect() and
1014 * the time we set up the inotify logic. But let's remember that we set up inotify now,
1015 * so that we don't do the connect() more than twice. */
1016 inotify_done = true;
1017
1018 } else
1019 return -errno;
1020 } else
1021 break;
1022 }
1023
1024 /* Yay, established, we don't need no inotify anymore! */
1025 bus_close_inotify_fd(b);
1026
1027 return bus_socket_start_auth(b);
1028 }
1029
1030 int bus_socket_exec(sd_bus *b) {
1031 int s[2], r;
1032
1033 assert(b);
1034 assert(b->input_fd < 0);
1035 assert(b->output_fd < 0);
1036 assert(b->exec_path);
1037 assert(b->busexec_pid == 0);
1038
1039 if (DEBUG_LOGGING) {
1040 _cleanup_free_ char *line = NULL;
1041
1042 if (b->exec_argv)
1043 line = quote_command_line(b->exec_argv, SHELL_ESCAPE_EMPTY);
1044
1045 log_debug("sd-bus: starting bus%s%s with %s%s",
1046 b->description ? " " : "", strempty(b->description),
1047 line ?: b->exec_path,
1048 b->exec_argv && !line ? "…" : "");
1049 }
1050
1051 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
1052 if (r < 0)
1053 return -errno;
1054
1055 r = safe_fork_full("(sd-busexec)",
1056 (int[]) { s[1], s[1], STDERR_FILENO },
1057 NULL, 0,
1058 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_REARRANGE_STDIO|FORK_RLIMIT_NOFILE_SAFE, &b->busexec_pid);
1059 if (r < 0) {
1060 safe_close_pair(s);
1061 return r;
1062 }
1063 if (r == 0) {
1064 /* Child */
1065
1066 if (b->exec_argv)
1067 execvp(b->exec_path, b->exec_argv);
1068 else
1069 execvp(b->exec_path, STRV_MAKE(b->exec_path));
1070
1071 _exit(EXIT_FAILURE);
1072 }
1073
1074 safe_close(s[1]);
1075 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
1076
1077 bus_socket_setup(b);
1078
1079 return bus_socket_start_auth(b);
1080 }
1081
1082 int bus_socket_take_fd(sd_bus *b) {
1083 assert(b);
1084
1085 bus_socket_setup(b);
1086
1087 return bus_socket_start_auth(b);
1088 }
1089
1090 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
1091 struct iovec *iov;
1092 ssize_t k;
1093 size_t n;
1094 unsigned j;
1095 int r;
1096
1097 assert(bus);
1098 assert(m);
1099 assert(idx);
1100 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1101
1102 if (*idx >= BUS_MESSAGE_SIZE(m))
1103 return 0;
1104
1105 r = bus_message_setup_iovec(m);
1106 if (r < 0)
1107 return r;
1108
1109 n = m->n_iovec * sizeof(struct iovec);
1110 iov = newa(struct iovec, n);
1111 memcpy_safe(iov, m->iovec, n);
1112
1113 j = 0;
1114 iovec_advance(iov, &j, *idx);
1115
1116 if (bus->prefer_writev)
1117 k = writev(bus->output_fd, iov, m->n_iovec);
1118 else {
1119 struct msghdr mh = {
1120 .msg_iov = iov,
1121 .msg_iovlen = m->n_iovec,
1122 };
1123
1124 if (m->n_fds > 0 && *idx == 0) {
1125 struct cmsghdr *control;
1126
1127 mh.msg_controllen = CMSG_SPACE(sizeof(int) * m->n_fds);
1128 mh.msg_control = alloca0(mh.msg_controllen);
1129 control = CMSG_FIRSTHDR(&mh);
1130 control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
1131 control->cmsg_level = SOL_SOCKET;
1132 control->cmsg_type = SCM_RIGHTS;
1133 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1134 }
1135
1136 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1137 if (k < 0 && errno == ENOTSOCK) {
1138 bus->prefer_writev = true;
1139 k = writev(bus->output_fd, iov, m->n_iovec);
1140 }
1141 }
1142
1143 if (k < 0)
1144 return ERRNO_IS_TRANSIENT(errno) ? 0 : -errno;
1145
1146 *idx += (size_t) k;
1147 return 1;
1148 }
1149
1150 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1151 uint32_t a, b;
1152 uint8_t e;
1153 uint64_t sum;
1154
1155 assert(bus);
1156 assert(need);
1157 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1158
1159 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1160 *need = sizeof(struct bus_header) + 8;
1161
1162 /* Minimum message size:
1163 *
1164 * Header +
1165 *
1166 * Method Call: +2 string headers
1167 * Signal: +3 string headers
1168 * Method Error: +1 string headers
1169 * +1 uint32 headers
1170 * Method Reply: +1 uint32 headers
1171 *
1172 * A string header is at least 9 bytes
1173 * A uint32 header is at least 8 bytes
1174 *
1175 * Hence the minimum message size of a valid message
1176 * is header + 8 bytes */
1177
1178 return 0;
1179 }
1180
1181 a = ((const uint32_t*) bus->rbuffer)[1];
1182 b = ((const uint32_t*) bus->rbuffer)[3];
1183
1184 e = ((const uint8_t*) bus->rbuffer)[0];
1185 if (e == BUS_LITTLE_ENDIAN) {
1186 a = le32toh(a);
1187 b = le32toh(b);
1188 } else if (e == BUS_BIG_ENDIAN) {
1189 a = be32toh(a);
1190 b = be32toh(b);
1191 } else
1192 return -EBADMSG;
1193
1194 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN8(b) + (uint64_t) a;
1195 if (sum >= BUS_MESSAGE_SIZE_MAX)
1196 return -ENOBUFS;
1197
1198 *need = (size_t) sum;
1199 return 0;
1200 }
1201
1202 static int bus_socket_make_message(sd_bus *bus, size_t size) {
1203 sd_bus_message *t = NULL;
1204 void *b;
1205 int r;
1206
1207 assert(bus);
1208 assert(bus->rbuffer_size >= size);
1209 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1210
1211 r = bus_rqueue_make_room(bus);
1212 if (r < 0)
1213 return r;
1214
1215 if (bus->rbuffer_size > size) {
1216 b = memdup((const uint8_t*) bus->rbuffer + size,
1217 bus->rbuffer_size - size);
1218 if (!b)
1219 return -ENOMEM;
1220 } else
1221 b = NULL;
1222
1223 r = bus_message_from_malloc(bus,
1224 bus->rbuffer, size,
1225 bus->fds, bus->n_fds,
1226 NULL,
1227 &t);
1228 if (r == -EBADMSG) {
1229 log_debug_errno(r, "Received invalid message from connection %s, dropping.", strna(bus->description));
1230 free(bus->rbuffer); /* We want to drop current rbuffer and proceed with whatever remains in b */
1231 } else if (r < 0) {
1232 free(b);
1233 return r;
1234 }
1235
1236 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
1237 bus->rbuffer = b;
1238 bus->rbuffer_size -= size;
1239
1240 bus->fds = NULL;
1241 bus->n_fds = 0;
1242
1243 if (t) {
1244 t->read_counter = ++bus->read_counter;
1245 bus->rqueue[bus->rqueue_size++] = bus_message_ref_queued(t, bus);
1246 sd_bus_message_unref(t);
1247 }
1248
1249 return 1;
1250 }
1251
1252 int bus_socket_read_message(sd_bus *bus) {
1253 struct msghdr mh;
1254 struct iovec iov = {};
1255 ssize_t k;
1256 size_t need;
1257 int r;
1258 void *b;
1259 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
1260 bool handle_cmsg = false;
1261
1262 assert(bus);
1263 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1264
1265 r = bus_socket_read_message_need(bus, &need);
1266 if (r < 0)
1267 return r;
1268
1269 if (bus->rbuffer_size >= need)
1270 return bus_socket_make_message(bus, need);
1271
1272 b = realloc(bus->rbuffer, need);
1273 if (!b)
1274 return -ENOMEM;
1275
1276 bus->rbuffer = b;
1277
1278 iov = IOVEC_MAKE((uint8_t *)bus->rbuffer + bus->rbuffer_size, need - bus->rbuffer_size);
1279
1280 if (bus->prefer_readv) {
1281 k = readv(bus->input_fd, &iov, 1);
1282 if (k < 0)
1283 k = -errno;
1284 } else {
1285 mh = (struct msghdr) {
1286 .msg_iov = &iov,
1287 .msg_iovlen = 1,
1288 .msg_control = &control,
1289 .msg_controllen = sizeof(control),
1290 };
1291
1292 k = recvmsg_safe(bus->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1293 if (k == -ENOTSOCK) {
1294 bus->prefer_readv = true;
1295 k = readv(bus->input_fd, &iov, 1);
1296 if (k < 0)
1297 k = -errno;
1298 } else
1299 handle_cmsg = true;
1300 }
1301 if (k < 0) {
1302 if (ERRNO_IS_TRANSIENT(k))
1303 return 0;
1304 return (int) k;
1305 }
1306 if (k == 0) {
1307 if (handle_cmsg)
1308 cmsg_close_all(&mh); /* On EOF we shouldn't have gotten an fd, but let's make sure */
1309 return -ECONNRESET;
1310 }
1311
1312 bus->rbuffer_size += k;
1313
1314 if (handle_cmsg) {
1315 struct cmsghdr *cmsg;
1316
1317 CMSG_FOREACH(cmsg, &mh)
1318 if (cmsg->cmsg_level == SOL_SOCKET &&
1319 cmsg->cmsg_type == SCM_RIGHTS) {
1320 int n, *f, i;
1321
1322 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1323
1324 if (!bus->can_fds) {
1325 /* Whut? We received fds but this
1326 * isn't actually enabled? Close them,
1327 * and fail */
1328
1329 close_many(CMSG_TYPED_DATA(cmsg, int), n);
1330 return -EIO;
1331 }
1332
1333 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
1334 if (!f) {
1335 close_many(CMSG_TYPED_DATA(cmsg, int), n);
1336 return -ENOMEM;
1337 }
1338
1339 for (i = 0; i < n; i++)
1340 f[bus->n_fds++] = fd_move_above_stdio(CMSG_TYPED_DATA(cmsg, int)[i]);
1341 bus->fds = f;
1342 } else
1343 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1344 cmsg->cmsg_level, cmsg->cmsg_type);
1345 }
1346
1347 r = bus_socket_read_message_need(bus, &need);
1348 if (r < 0)
1349 return r;
1350
1351 if (bus->rbuffer_size >= need)
1352 return bus_socket_make_message(bus, need);
1353
1354 return 1;
1355 }
1356
1357 int bus_socket_process_opening(sd_bus *b) {
1358 int error = 0, events, r;
1359 socklen_t slen = sizeof(error);
1360
1361 assert(b->state == BUS_OPENING);
1362
1363 events = fd_wait_for_event(b->output_fd, POLLOUT, 0);
1364 if (events < 0) {
1365 if (ERRNO_IS_TRANSIENT(events))
1366 return 0;
1367 return events;
1368 }
1369 if (!(events & (POLLOUT|POLLERR|POLLHUP)))
1370 return 0;
1371
1372 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1373 if (r < 0)
1374 b->last_connect_error = errno;
1375 else if (error != 0)
1376 b->last_connect_error = error;
1377 else if (events & (POLLERR|POLLHUP))
1378 b->last_connect_error = ECONNREFUSED;
1379 else
1380 return bus_socket_start_auth(b);
1381
1382 return bus_next_address(b);
1383 }
1384
1385 int bus_socket_process_authenticating(sd_bus *b) {
1386 int r;
1387
1388 assert(b);
1389 assert(b->state == BUS_AUTHENTICATING);
1390
1391 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1392 return -ETIMEDOUT;
1393
1394 r = bus_socket_write_auth(b);
1395 if (r != 0)
1396 return r;
1397
1398 return bus_socket_read_auth(b);
1399 }
1400
1401 int bus_socket_process_watch_bind(sd_bus *b) {
1402 int r, q;
1403
1404 assert(b);
1405 assert(b->state == BUS_WATCH_BIND);
1406 assert(b->inotify_fd >= 0);
1407
1408 r = flush_fd(b->inotify_fd);
1409 if (r <= 0)
1410 return r;
1411
1412 log_debug("Got inotify event on bus %s.", strna(b->description));
1413
1414 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1415 * to it again */
1416
1417 r = bus_socket_connect(b);
1418 if (r < 0)
1419 return r;
1420
1421 q = bus_attach_io_events(b);
1422 if (q < 0)
1423 return q;
1424
1425 q = bus_attach_inotify_event(b);
1426 if (q < 0)
1427 return q;
1428
1429 return r;
1430 }