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