]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/libsystemd/sd-bus/bus-socket.c
manager: use _NEG_ macros to reduce indentation, reword comments, drop parens
[thirdparty/systemd.git] / src / libsystemd / sd-bus / bus-socket.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7e3212d
LP
2
3#include <endian.h>
07630cea 4#include <poll.h>
a7e3212d
LP
5#include <stdlib.h>
6#include <unistd.h>
a7e3212d 7
07630cea 8#include "sd-bus.h"
24882e06 9#include "sd-daemon.h"
07630cea 10
b5efdb8a 11#include "alloc-util.h"
07630cea
LP
12#include "bus-internal.h"
13#include "bus-message.h"
3ffd4af2 14#include "bus-socket.h"
87fa2e21 15#include "escape.h"
3ffd4af2 16#include "fd-util.h"
f97b34a6 17#include "format-util.h"
8a5cd31e 18#include "fs-util.h"
15a5e950 19#include "hexdecoct.h"
8a5cd31e 20#include "io-util.h"
a7e3212d 21#include "macro.h"
0a970718 22#include "memory-util.h"
8a5cd31e 23#include "path-util.h"
dccca82b 24#include "process-util.h"
a0cb3358 25#include "random-util.h"
24882e06 26#include "signal-util.h"
15a5e950 27#include "stdio-util.h"
07630cea 28#include "string-util.h"
b1d4f8e1 29#include "user-util.h"
07630cea 30#include "utf8.h"
a7e3212d 31
aec6d91f
LP
32#define SNDBUF_SIZE (8*1024*1024)
33
2181a7f5 34static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
a7e3212d
LP
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
5cfa2c3d 47 *i = IOVEC_MAKE(NULL, 0);
a7e3212d 48
313cefa1 49 (*idx)++;
a7e3212d
LP
50 }
51}
52
bc7fd8cd 53static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
2100fa10
LP
54 assert(m);
55 assert(p);
56 assert(sz > 0);
57
5cfa2c3d 58 m->iovec[m->n_iovec++] = IOVEC_MAKE((void*) p, sz);
bc7fd8cd
LP
59
60 return 0;
2100fa10
LP
61}
62
bc7fd8cd
LP
63static int bus_message_setup_iovec(sd_bus_message *m) {
64 struct bus_body_part *part;
13c299d3 65 unsigned n, i;
bc7fd8cd
LP
66 int r;
67
2100fa10
LP
68 assert(m);
69 assert(m->sealed);
70
71 if (m->n_iovec > 0)
bc7fd8cd
LP
72 return 0;
73
74 assert(!m->iovec);
2100fa10 75
c91cb83c 76 n = 1 + m->n_body_parts;
bc7fd8cd
LP
77 if (n < ELEMENTSOF(m->iovec_fixed))
78 m->iovec = m->iovec_fixed;
79 else {
80 m->iovec = new(struct iovec, n);
66b26c5c
LP
81 if (!m->iovec) {
82 r = -ENOMEM;
83 goto fail;
84 }
bc7fd8cd 85 }
2100fa10 86
c91cb83c 87 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
bc7fd8cd 88 if (r < 0)
66b26c5c 89 goto fail;
2100fa10 90
9b29bb68 91 MESSAGE_FOREACH_PART(part, i, m) {
66b26c5c
LP
92 r = bus_body_part_map(part);
93 if (r < 0)
94 goto fail;
95
bc7fd8cd
LP
96 r = append_iovec(m, part->data, part->size);
97 if (r < 0)
66b26c5c 98 goto fail;
bc7fd8cd
LP
99 }
100
101 assert(n == m->n_iovec);
102
103 return 0;
66b26c5c
LP
104
105fail:
106 m->poisoned = true;
107 return r;
2100fa10
LP
108}
109
2181a7f5
LP
110bool 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
2181a7f5 127static int bus_socket_auth_verify_client(sd_bus *b) {
347f4824 128 char *l, *lines[4] = {};
a7e3212d 129 sd_id128_t peer;
347f4824 130 size_t i, n;
a7e3212d
LP
131 int r;
132
2181a7f5
LP
133 assert(b);
134
1ed4723d 135 /*
347f4824
DR
136 * We expect up to three response lines:
137 * "DATA\r\n" (optional)
1ed4723d
DR
138 * "OK <server-id>\r\n"
139 * "AGREE_UNIX_FD\r\n" (optional)
140 */
a7e3212d 141
347f4824
DR
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;
a7e3212d
LP
150 }
151
347f4824
DR
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
1ed4723d 185 return -EPERM;
347f4824 186 }
a7e3212d 187
1ed4723d 188 /* Now check the OK line. */
347f4824 189 l = lines[i++];
1ed4723d 190
347f4824 191 if (lines[i] - l != 3 + 32 + 2)
a7e3212d 192 return -EPERM;
347f4824 193 if (memcmp(l, "OK ", 3))
a7e3212d
LP
194 return -EPERM;
195
2181a7f5
LP
196 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
197
347f4824 198 for (unsigned j = 0; j < 32; j += 2) {
a7e3212d
LP
199 int x, y;
200
347f4824
DR
201 x = unhexchar(l[3 + j]);
202 y = unhexchar(l[3 + j + 1]);
a7e3212d
LP
203
204 if (x < 0 || y < 0)
205 return -EINVAL;
206
347f4824 207 peer.bytes[j/2] = ((uint8_t) x << 4 | (uint8_t) y);
a7e3212d
LP
208 }
209
3bbaff3e 210 if (!sd_id128_is_null(b->server_id) &&
98178d39 211 !sd_id128_equal(b->server_id, peer))
a7e3212d
LP
212 return -EPERM;
213
98178d39 214 b->server_id = peer;
a7e3212d 215
1ed4723d 216 /* And possibly check the third line, too */
347f4824
DR
217 if (b->accept_fd) {
218 l = lines[i++];
219 b->can_fds = !!memory_startswith(l, lines[i] - l, "AGREE_UNIX_FD");
220 }
a7e3212d 221
347f4824 222 assert(i == n);
a7e3212d 223
347f4824
DR
224 b->rbuffer_size -= (lines[i] - (char*) b->rbuffer);
225 memmove(b->rbuffer, lines[i], b->rbuffer_size);
a7e3212d
LP
226
227 r = bus_start_running(b);
228 if (r < 0)
229 return r;
230
231 return 1;
232}
233
2181a7f5
LP
234static 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
244static bool line_begins(const char *s, size_t m, const char *word) {
d27b725a 245 const char *p;
2181a7f5 246
d27b725a 247 p = memory_startswith(s, m, word);
3f10c662 248 return p && (p == (s + m) || *p == ' ');
2181a7f5
LP
249}
250
251static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
252 _cleanup_free_ char *token = NULL;
30494563
TG
253 size_t len;
254 int r;
2181a7f5
LP
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;
2181a7f5 267
30494563
TG
268 r = unhexmem(p, l, (void **) &token, &len);
269 if (r < 0)
270 return 0;
271
272 if (memchr(token, 0, len))
2181a7f5
LP
273 return 0;
274
275 return !!utf8_is_valid(token);
276}
277
278static int verify_external_token(sd_bus *b, const char *p, size_t l) {
279 _cleanup_free_ char *token = NULL;
30494563 280 size_t len;
2181a7f5
LP
281 uid_t u;
282 int r;
283
b3d06b92 284 /* We don't do any real authentication here. Instead, if
be7148eb 285 * the owner of this bus wanted authentication they should have
2181a7f5
LP
286 * checked SO_PEERCRED before even creating the bus object. */
287
8411d2a2 288 if (!b->anonymous_auth && !b->ucred_valid)
2181a7f5
LP
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
30494563
TG
300 r = unhexmem(p, l, (void**) &token, &len);
301 if (r < 0)
302 return 0;
2181a7f5 303
30494563 304 if (memchr(token, 0, len))
2181a7f5
LP
305 return 0;
306
307 r = parse_uid(token, &u);
308 if (r < 0)
309 return 0;
310
8411d2a2
LP
311 /* We ignore the passed value if anonymous authentication is
312 * on anyway. */
313 if (!b->anonymous_auth && u != b->ucred.uid)
2181a7f5
LP
314 return 0;
315
316 return 1;
317}
318
319static 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 */
945c2931 327 assert(IN_SET(b->auth_index, 0, 1));
2181a7f5
LP
328
329 l = strlen(t);
330 p = malloc(b->auth_iovec[0].iov_len + l);
331 if (!p)
332 return -ENOMEM;
333
75f32f04 334 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
2181a7f5
LP
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
d6f2cd67 340 free_and_replace(b->auth_buffer, p);
2181a7f5
LP
341 b->auth_index = 0;
342 return 0;
343}
344
345static int bus_socket_auth_write_ok(sd_bus *b) {
346 char t[3 + 32 + 2 + 1];
347
348 assert(b);
349
5ffa8c81 350 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
2181a7f5
LP
351
352 return bus_socket_auth_write(b, t);
353}
354
355static 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
2b4ac889 364 if (b->rbuffer_size < 1)
2181a7f5
LP
365 return 0;
366
367 /* First char must be a NUL byte */
368 if (*(char*) b->rbuffer != 0)
369 return -EIO;
370
2b4ac889
LP
371 if (b->rbuffer_size < 3)
372 return 0;
373
2181a7f5
LP
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;
e8b08edc 381 e = memmem_safe(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
2181a7f5
LP
382 if (!e)
383 return processed;
384
385 l = e - line;
386
387 if (line_begins(line, l, "AUTH ANONYMOUS")) {
388
3cacdab9
DR
389 r = verify_anonymous_token(b,
390 line + strlen("AUTH ANONYMOUS"),
391 l - strlen("AUTH ANONYMOUS"));
2181a7f5
LP
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;
2010873b
DR
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);
2181a7f5
LP
402 }
403
404 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
405
3cacdab9
DR
406 r = verify_external_token(b,
407 line + strlen("AUTH EXTERNAL"),
408 l - strlen("AUTH EXTERNAL"));
2181a7f5
LP
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;
2010873b
DR
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);
2181a7f5
LP
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")) {
c7db1984 466 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
2181a7f5
LP
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
484static 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
4e2baf2f
MV
493static 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
a7e3212d
LP
528static int bus_socket_read_auth(sd_bus *b) {
529 struct msghdr mh;
7f4e6a1c 530 struct iovec iov = {};
a7e3212d
LP
531 size_t n;
532 ssize_t k;
533 int r;
534 void *p;
fb29cdbe 535 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
15d5af81 536 bool handle_cmsg = false;
a7e3212d
LP
537
538 assert(b);
2181a7f5 539 assert(b->state == BUS_AUTHENTICATING);
a7e3212d
LP
540
541 r = bus_socket_auth_verify(b);
542 if (r != 0)
543 return r;
544
9607d947 545 n = MAX(256u, b->rbuffer_size * 2);
a7e3212d
LP
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
5cfa2c3d 559 iov = IOVEC_MAKE((uint8_t *)b->rbuffer + b->rbuffer_size, n - b->rbuffer_size);
a7e3212d 560
c1093c34 561 if (b->prefer_readv) {
15d5af81 562 k = readv(b->input_fd, &iov, 1);
c1093c34
LP
563 if (k < 0)
564 k = -errno;
565 } else {
41ab8c67
LP
566 mh = (struct msghdr) {
567 .msg_iov = &iov,
568 .msg_iovlen = 1,
569 .msg_control = &control,
570 .msg_controllen = sizeof(control),
571 };
15d5af81 572
3691bcf3
LP
573 k = recvmsg_safe(b->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
574 if (k == -ENOTSOCK) {
15d5af81
LP
575 b->prefer_readv = true;
576 k = readv(b->input_fd, &iov, 1);
3691bcf3
LP
577 if (k < 0)
578 k = -errno;
15d5af81
LP
579 } else
580 handle_cmsg = true;
581 }
b3d06b92
YW
582 if (k < 0) {
583 if (ERRNO_IS_TRANSIENT(k))
584 return 0;
3691bcf3 585 return (int) k;
b3d06b92 586 }
3691bcf3
LP
587 if (k == 0) {
588 if (handle_cmsg)
589 cmsg_close_all(&mh); /* paranoia, we shouldn't have gotten any fds on EOF */
a7e3212d 590 return -ECONNRESET;
3691bcf3 591 }
a7e3212d
LP
592
593 b->rbuffer_size += k;
594
2a1288ff
LP
595 if (handle_cmsg) {
596 struct cmsghdr *cmsg;
597
598 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
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);
b1d02191 607 close_many(CMSG_TYPED_DATA(cmsg, int), j);
15d5af81 608 return -EIO;
d868f2a3
ZJS
609 } else
610 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
611 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 612 }
2181a7f5 613
a7e3212d
LP
614 r = bus_socket_auth_verify(b);
615 if (r != 0)
616 return r;
617
618 return 1;
619}
620
8f04d2eb 621void bus_socket_setup(sd_bus *b) {
a7e3212d
LP
622 assert(b);
623
aec6d91f 624 /* Increase the buffers to 8 MB */
28e7e934 625 (void) fd_increase_rxbuf(b->input_fd, SNDBUF_SIZE);
6ae22ffb 626 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
a7e3212d 627
e1d337d4 628 b->message_version = 1;
0f437184 629 b->message_endian = 0;
8f04d2eb 630}
e1d337d4 631
8f04d2eb 632static void bus_get_peercred(sd_bus *b) {
c4e6556c
ZJS
633 int r;
634
8f04d2eb 635 assert(b);
18ac4643
LP
636 assert(!b->ucred_valid);
637 assert(!b->label);
f5fbe71d 638 assert(b->n_groups == SIZE_MAX);
8f04d2eb
LP
639
640 /* Get the peer for socketpair() sockets */
eff05270 641 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
c4e6556c
ZJS
642
643 /* Get the SELinux context of the peer */
db7d1dca 644 r = getpeersec(b->input_fd, &b->label);
18ac4643 645 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
db7d1dca 646 log_debug_errno(r, "Failed to determine peer security context: %m");
18ac4643
LP
647
648 /* Get the list of auxiliary groups of the peer */
649 r = getpeergroups(b->input_fd, &b->groups);
c599b325 650 if (r >= 0)
18ac4643 651 b->n_groups = (size_t) r;
c599b325
ZJS
652 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
653 log_debug_errno(r, "Failed to determine peer's group list: %m");
c32f9648
LP
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;
a7e3212d
LP
665}
666
2181a7f5 667static int bus_socket_start_auth_client(sd_bus *b) {
1ed4723d
DR
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 */
347f4824
DR
674 /* HEX a n o n y m o u s */
675 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
1ed4723d
DR
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;
a7e3212d
LP
688
689 assert(b);
690
1ed4723d
DR
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);
a7e3212d 695
c7db1984 696 if (b->accept_fd)
1ed4723d 697 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd);
a7e3212d 698
1ed4723d 699 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_begin);
a7e3212d
LP
700
701 return bus_socket_write_auth(b);
702}
703
a7893c6b 704int bus_socket_start_auth(sd_bus *b) {
2181a7f5
LP
705 assert(b);
706
8f04d2eb
LP
707 bus_get_peercred(b);
708
3e0e196e 709 bus_set_state(b, BUS_AUTHENTICATING);
036d61b3 710 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
2181a7f5 711
9ab32f9d 712 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 713 b->accept_fd = false;
2181a7f5 714
9ab32f9d
LP
715 if (b->output_fd != b->input_fd)
716 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 717 b->accept_fd = false;
e82c9509 718
2181a7f5
LP
719 if (b->is_server)
720 return bus_socket_read_auth(b);
721 else
722 return bus_socket_start_auth_client(b);
723}
724
8a5cd31e
LP
725static int bus_socket_inotify_setup(sd_bus *b) {
726 _cleanup_free_ int *new_watches = NULL;
727 _cleanup_free_ char *absolute = NULL;
319a4f4b 728 size_t n = 0, done = 0, i;
8a5cd31e
LP
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;
7fe2903c
LP
749
750 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
8a5cd31e
LP
751 }
752
753 /* Make sure the path is NUL terminated */
2f82562b
LP
754 p = strndupa_safe(b->sockaddr.un.sun_path,
755 sizeof(b->sockaddr.un.sun_path));
8a5cd31e
LP
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
319a4f4b 766 if (!GREEDY_REALLOC(new_watches, n + 1)) {
8a5cd31e
LP
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
319a4f4b 815 if (!GREEDY_REALLOC(new_watches, n + 1)) {
8a5cd31e
LP
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
945403e6 827 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
8a5cd31e
LP
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
d6f2cd67 870 free_and_replace(absolute, c);
8a5cd31e
LP
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
897fail:
898 bus_close_inotify_fd(b);
899 return r;
900}
901
a0cb3358
LP
902static 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:
da890466 921 * - a random 64-bit value (to avoid collisions)
a0cb3358
LP
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
a7e3212d 946int bus_socket_connect(sd_bus *b) {
8a5cd31e 947 bool inotify_done = false;
a7e3212d
LP
948 int r;
949
950 assert(b);
a7e3212d 951
8a5cd31e
LP
952 for (;;) {
953 assert(b->input_fd < 0);
954 assert(b->output_fd < 0);
955 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
a7e3212d 956
165fee86
ZJS
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
8a5cd31e
LP
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;
e82c9509 967
a0cb3358
LP
968 r = bind_description(b, b->input_fd, b->sockaddr.sa.sa_family);
969 if (r < 0)
970 return r;
971
7fe2903c
LP
972 b->input_fd = fd_move_above_stdio(b->input_fd);
973
8a5cd31e
LP
974 b->output_fd = b->input_fd;
975 bus_socket_setup(b);
a7e3212d 976
8a5cd31e
LP
977 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
978 if (errno == EINPROGRESS) {
a7e3212d 979
8a5cd31e
LP
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. */
3e0e196e 987 bus_set_state(b, BUS_OPENING);
8a5cd31e
LP
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. */
3e0e196e 1003 bus_set_state(b, BUS_WATCH_BIND);
8a5cd31e
LP
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;
a7e3212d
LP
1022 }
1023
8a5cd31e
LP
1024 /* Yay, established, we don't need no inotify anymore! */
1025 bus_close_inotify_fd(b);
1026
a7e3212d
LP
1027 return bus_socket_start_auth(b);
1028}
1029
1030int bus_socket_exec(sd_bus *b) {
e82c9509 1031 int s[2], r;
a7e3212d
LP
1032
1033 assert(b);
e82c9509
LP
1034 assert(b->input_fd < 0);
1035 assert(b->output_fd < 0);
a7e3212d 1036 assert(b->exec_path);
392cf1d0 1037 assert(b->busexec_pid == 0);
a7e3212d 1038
87fa2e21
ZJS
1039 if (DEBUG_LOGGING) {
1040 _cleanup_free_ char *line = NULL;
1041
1042 if (b->exec_argv)
4ef15008 1043 line = quote_command_line(b->exec_argv, SHELL_ESCAPE_EMPTY);
87fa2e21
ZJS
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 }
165fee86 1050
e82c9509
LP
1051 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
1052 if (r < 0)
a7e3212d
LP
1053 return -errno;
1054
911f8f01 1055 r = safe_fork_full("(sd-busexec)",
0c2aedb4
YW
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);
4c253ed1 1059 if (r < 0) {
3d94f76c 1060 safe_close_pair(s);
4c253ed1 1061 return r;
a7e3212d 1062 }
4c253ed1 1063 if (r == 0) {
a7e3212d
LP
1064 /* Child */
1065
a7e3212d
LP
1066 if (b->exec_argv)
1067 execvp(b->exec_path, b->exec_argv);
87fa2e21
ZJS
1068 else
1069 execvp(b->exec_path, STRV_MAKE(b->exec_path));
a7e3212d
LP
1070
1071 _exit(EXIT_FAILURE);
1072 }
1073
03e334a1 1074 safe_close(s[1]);
7fe2903c 1075 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
a7e3212d 1076
8f04d2eb 1077 bus_socket_setup(b);
e1d337d4 1078
a7e3212d
LP
1079 return bus_socket_start_auth(b);
1080}
1081
1082int bus_socket_take_fd(sd_bus *b) {
a7e3212d
LP
1083 assert(b);
1084
8f04d2eb 1085 bus_socket_setup(b);
a7e3212d
LP
1086
1087 return bus_socket_start_auth(b);
1088}
1089
1090int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
a7e3212d
LP
1091 struct iovec *iov;
1092 ssize_t k;
1093 size_t n;
1094 unsigned j;
bc7fd8cd 1095 int r;
a7e3212d
LP
1096
1097 assert(bus);
1098 assert(m);
1099 assert(idx);
945c2931 1100 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1101
6629161f 1102 if (*idx >= BUS_MESSAGE_SIZE(m))
a7e3212d 1103 return 0;
a7e3212d 1104
bc7fd8cd
LP
1105 r = bus_message_setup_iovec(m);
1106 if (r < 0)
1107 return r;
2100fa10 1108
a7e3212d 1109 n = m->n_iovec * sizeof(struct iovec);
6e9417f5 1110 iov = newa(struct iovec, n);
75f32f04 1111 memcpy_safe(iov, m->iovec, n);
a7e3212d
LP
1112
1113 j = 0;
1114 iovec_advance(iov, &j, *idx);
1115
15d5af81
LP
1116 if (bus->prefer_writev)
1117 k = writev(bus->output_fd, iov, m->n_iovec);
1118 else {
7f4e6a1c
ZJS
1119 struct msghdr mh = {
1120 .msg_iov = iov,
1121 .msg_iovlen = m->n_iovec,
1122 };
15d5af81 1123
f29eef2e 1124 if (m->n_fds > 0 && *idx == 0) {
15d5af81 1125 struct cmsghdr *control;
15d5af81 1126
a258f491
LP
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);
15d5af81
LP
1131 control->cmsg_level = SOL_SOCKET;
1132 control->cmsg_type = SCM_RIGHTS;
15d5af81
LP
1133 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1134 }
1135
15d5af81
LP
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 }
a7e3212d 1142
a7e3212d 1143 if (k < 0)
b3d06b92 1144 return ERRNO_IS_TRANSIENT(errno) ? 0 : -errno;
a7e3212d
LP
1145
1146 *idx += (size_t) k;
1147 return 1;
1148}
1149
1150static 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);
945c2931 1157 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
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];
0461f8cd 1185 if (e == BUS_LITTLE_ENDIAN) {
a7e3212d
LP
1186 a = le32toh(a);
1187 b = le32toh(b);
0461f8cd 1188 } else if (e == BUS_BIG_ENDIAN) {
a7e3212d
LP
1189 a = be32toh(a);
1190 b = be32toh(b);
1191 } else
1192 return -EBADMSG;
1193
dc7be332 1194 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN8(b) + (uint64_t) a;
a7e3212d
LP
1195 if (sum >= BUS_MESSAGE_SIZE_MAX)
1196 return -ENOBUFS;
1197
1198 *need = (size_t) sum;
1199 return 0;
1200}
1201
7d22c717 1202static int bus_socket_make_message(sd_bus *bus, size_t size) {
6d586a13 1203 sd_bus_message *t = NULL;
a7e3212d
LP
1204 void *b;
1205 int r;
1206
1207 assert(bus);
a7e3212d 1208 assert(bus->rbuffer_size >= size);
945c2931 1209 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1210
7adc46fc
LP
1211 r = bus_rqueue_make_room(bus);
1212 if (r < 0)
1213 return r;
1214
a7e3212d
LP
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
df2d202e
LP
1223 r = bus_message_from_malloc(bus,
1224 bus->rbuffer, size,
a7e3212d 1225 bus->fds, bus->n_fds,
038f9863 1226 NULL,
a7e3212d 1227 &t);
3dec5201 1228 if (r == -EBADMSG) {
6d586a13 1229 log_debug_errno(r, "Received invalid message from connection %s, dropping.", strna(bus->description));
3dec5201
ZJS
1230 free(bus->rbuffer); /* We want to drop current rbuffer and proceed with whatever remains in b */
1231 } else if (r < 0) {
a7e3212d
LP
1232 free(b);
1233 return r;
1234 }
1235
3dec5201 1236 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
a7e3212d
LP
1237 bus->rbuffer = b;
1238 bus->rbuffer_size -= size;
1239
1240 bus->fds = NULL;
1241 bus->n_fds = 0;
1242
c1757a70 1243 if (t) {
f1617a3b 1244 t->read_counter = ++bus->read_counter;
c1757a70
LP
1245 bus->rqueue[bus->rqueue_size++] = bus_message_ref_queued(t, bus);
1246 sd_bus_message_unref(t);
1247 }
7d22c717 1248
a7e3212d
LP
1249 return 1;
1250}
1251
7d22c717 1252int bus_socket_read_message(sd_bus *bus) {
a7e3212d 1253 struct msghdr mh;
7f4e6a1c 1254 struct iovec iov = {};
a7e3212d
LP
1255 ssize_t k;
1256 size_t need;
1257 int r;
1258 void *b;
fb29cdbe 1259 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
4d3a5b10 1260 bool handle_cmsg = false;
a7e3212d
LP
1261
1262 assert(bus);
945c2931 1263 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1264
1265 r = bus_socket_read_message_need(bus, &need);
1266 if (r < 0)
1267 return r;
1268
1269 if (bus->rbuffer_size >= need)
7d22c717 1270 return bus_socket_make_message(bus, need);
a7e3212d
LP
1271
1272 b = realloc(bus->rbuffer, need);
1273 if (!b)
1274 return -ENOMEM;
1275
1276 bus->rbuffer = b;
1277
5cfa2c3d 1278 iov = IOVEC_MAKE((uint8_t *)bus->rbuffer + bus->rbuffer_size, need - bus->rbuffer_size);
a7e3212d 1279
c1093c34 1280 if (bus->prefer_readv) {
15d5af81 1281 k = readv(bus->input_fd, &iov, 1);
c1093c34
LP
1282 if (k < 0)
1283 k = -errno;
1284 } else {
41ab8c67
LP
1285 mh = (struct msghdr) {
1286 .msg_iov = &iov,
1287 .msg_iovlen = 1,
1288 .msg_control = &control,
1289 .msg_controllen = sizeof(control),
1290 };
15d5af81 1291
3691bcf3
LP
1292 k = recvmsg_safe(bus->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1293 if (k == -ENOTSOCK) {
15d5af81
LP
1294 bus->prefer_readv = true;
1295 k = readv(bus->input_fd, &iov, 1);
3691bcf3
LP
1296 if (k < 0)
1297 k = -errno;
15d5af81
LP
1298 } else
1299 handle_cmsg = true;
1300 }
b3d06b92
YW
1301 if (k < 0) {
1302 if (ERRNO_IS_TRANSIENT(k))
1303 return 0;
3691bcf3 1304 return (int) k;
b3d06b92 1305 }
3691bcf3
LP
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 */
a7e3212d 1309 return -ECONNRESET;
3691bcf3 1310 }
a7e3212d
LP
1311
1312 bus->rbuffer_size += k;
1313
2a1288ff
LP
1314 if (handle_cmsg) {
1315 struct cmsghdr *cmsg;
1316
1317 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
1318 if (cmsg->cmsg_level == SOL_SOCKET &&
1319 cmsg->cmsg_type == SCM_RIGHTS) {
7fe2903c 1320 int n, *f, i;
15d5af81
LP
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
b1d02191 1329 close_many(CMSG_TYPED_DATA(cmsg, int), n);
15d5af81
LP
1330 return -EIO;
1331 }
1332
62d74c78 1333 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
15d5af81 1334 if (!f) {
b1d02191 1335 close_many(CMSG_TYPED_DATA(cmsg, int), n);
15d5af81
LP
1336 return -ENOMEM;
1337 }
1338
7fe2903c 1339 for (i = 0; i < n; i++)
b1d02191 1340 f[bus->n_fds++] = fd_move_above_stdio(CMSG_TYPED_DATA(cmsg, int)[i]);
15d5af81 1341 bus->fds = f;
d868f2a3
ZJS
1342 } else
1343 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1344 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 1345 }
a7e3212d
LP
1346
1347 r = bus_socket_read_message_need(bus, &need);
1348 if (r < 0)
1349 return r;
1350
1351 if (bus->rbuffer_size >= need)
7d22c717 1352 return bus_socket_make_message(bus, need);
a7e3212d
LP
1353
1354 return 1;
1355}
1356
1357int bus_socket_process_opening(sd_bus *b) {
0f2d351f 1358 int error = 0, events, r;
a7e3212d 1359 socklen_t slen = sizeof(error);
a7e3212d 1360
a7e3212d
LP
1361 assert(b->state == BUS_OPENING);
1362
0f2d351f 1363 events = fd_wait_for_event(b->output_fd, POLLOUT, 0);
3022916b
LP
1364 if (events < 0) {
1365 if (ERRNO_IS_TRANSIENT(events))
1366 return 0;
0f2d351f 1367 return events;
3022916b 1368 }
0f2d351f 1369 if (!(events & (POLLOUT|POLLERR|POLLHUP)))
a7e3212d
LP
1370 return 0;
1371
e82c9509 1372 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
a7e3212d
LP
1373 if (r < 0)
1374 b->last_connect_error = errno;
1375 else if (error != 0)
1376 b->last_connect_error = error;
0f2d351f 1377 else if (events & (POLLERR|POLLHUP))
a7e3212d
LP
1378 b->last_connect_error = ECONNREFUSED;
1379 else
1380 return bus_socket_start_auth(b);
1381
1382 return bus_next_address(b);
1383}
1384
1385int 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}
8a5cd31e
LP
1400
1401int 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}