]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/libsystemd/sd-bus/bus-socket.c
tree-wide: modernizations with RET_NERRNO()
[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"
595225af 25#include "rlimit-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
340 free(b->auth_buffer);
341 b->auth_buffer = p;
342 b->auth_index = 0;
343 return 0;
344}
345
346static int bus_socket_auth_write_ok(sd_bus *b) {
347 char t[3 + 32 + 2 + 1];
348
349 assert(b);
350
5ffa8c81 351 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
2181a7f5
LP
352
353 return bus_socket_auth_write(b, t);
354}
355
356static int bus_socket_auth_verify_server(sd_bus *b) {
357 char *e;
358 const char *line;
359 size_t l;
360 bool processed = false;
361 int r;
362
363 assert(b);
364
2b4ac889 365 if (b->rbuffer_size < 1)
2181a7f5
LP
366 return 0;
367
368 /* First char must be a NUL byte */
369 if (*(char*) b->rbuffer != 0)
370 return -EIO;
371
2b4ac889
LP
372 if (b->rbuffer_size < 3)
373 return 0;
374
2181a7f5
LP
375 /* Begin with the first line */
376 if (b->auth_rbegin <= 0)
377 b->auth_rbegin = 1;
378
379 for (;;) {
380 /* Check if line is complete */
381 line = (char*) b->rbuffer + b->auth_rbegin;
e8b08edc 382 e = memmem_safe(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
2181a7f5
LP
383 if (!e)
384 return processed;
385
386 l = e - line;
387
388 if (line_begins(line, l, "AUTH ANONYMOUS")) {
389
3cacdab9
DR
390 r = verify_anonymous_token(b,
391 line + strlen("AUTH ANONYMOUS"),
392 l - strlen("AUTH ANONYMOUS"));
2181a7f5
LP
393 if (r < 0)
394 return r;
395 if (r == 0)
396 r = bus_socket_auth_write(b, "REJECTED\r\n");
397 else {
398 b->auth = BUS_AUTH_ANONYMOUS;
2010873b
DR
399 if (l <= strlen("AUTH ANONYMOUS"))
400 r = bus_socket_auth_write(b, "DATA\r\n");
401 else
402 r = bus_socket_auth_write_ok(b);
2181a7f5
LP
403 }
404
405 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
406
3cacdab9
DR
407 r = verify_external_token(b,
408 line + strlen("AUTH EXTERNAL"),
409 l - strlen("AUTH EXTERNAL"));
2181a7f5
LP
410 if (r < 0)
411 return r;
412 if (r == 0)
413 r = bus_socket_auth_write(b, "REJECTED\r\n");
414 else {
415 b->auth = BUS_AUTH_EXTERNAL;
2010873b
DR
416 if (l <= strlen("AUTH EXTERNAL"))
417 r = bus_socket_auth_write(b, "DATA\r\n");
418 else
419 r = bus_socket_auth_write_ok(b);
2181a7f5
LP
420 }
421
422 } else if (line_begins(line, l, "AUTH"))
423 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
424 else if (line_equals(line, l, "CANCEL") ||
425 line_begins(line, l, "ERROR")) {
426
427 b->auth = _BUS_AUTH_INVALID;
428 r = bus_socket_auth_write(b, "REJECTED\r\n");
429
430 } else if (line_equals(line, l, "BEGIN")) {
431
432 if (b->auth == _BUS_AUTH_INVALID)
433 r = bus_socket_auth_write(b, "ERROR\r\n");
434 else {
435 /* We can't leave from the auth phase
436 * before we haven't written
437 * everything queued, so let's check
438 * that */
439
440 if (bus_socket_auth_needs_write(b))
441 return 1;
442
443 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
444 memmove(b->rbuffer, e + 2, b->rbuffer_size);
445 return bus_start_running(b);
446 }
447
448 } else if (line_begins(line, l, "DATA")) {
449
450 if (b->auth == _BUS_AUTH_INVALID)
451 r = bus_socket_auth_write(b, "ERROR\r\n");
452 else {
453 if (b->auth == BUS_AUTH_ANONYMOUS)
454 r = verify_anonymous_token(b, line + 4, l - 4);
455 else
456 r = verify_external_token(b, line + 4, l - 4);
457
458 if (r < 0)
459 return r;
460 if (r == 0) {
461 b->auth = _BUS_AUTH_INVALID;
462 r = bus_socket_auth_write(b, "REJECTED\r\n");
463 } else
464 r = bus_socket_auth_write_ok(b);
465 }
466 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
c7db1984 467 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
2181a7f5
LP
468 r = bus_socket_auth_write(b, "ERROR\r\n");
469 else {
470 b->can_fds = true;
471 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
472 }
473 } else
474 r = bus_socket_auth_write(b, "ERROR\r\n");
475
476 if (r < 0)
477 return r;
478
479 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
480
481 processed = true;
482 }
483}
484
485static int bus_socket_auth_verify(sd_bus *b) {
486 assert(b);
487
488 if (b->is_server)
489 return bus_socket_auth_verify_server(b);
490 else
491 return bus_socket_auth_verify_client(b);
492}
493
4e2baf2f
MV
494static int bus_socket_write_auth(sd_bus *b) {
495 ssize_t k;
496
497 assert(b);
498 assert(b->state == BUS_AUTHENTICATING);
499
500 if (!bus_socket_auth_needs_write(b))
501 return 0;
502
503 if (b->prefer_writev)
504 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
505 else {
506 struct msghdr mh = {
507 .msg_iov = b->auth_iovec + b->auth_index,
508 .msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index,
509 };
510
511 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
512 if (k < 0 && errno == ENOTSOCK) {
513 b->prefer_writev = true;
514 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
515 }
516 }
517
518 if (k < 0)
519 return ERRNO_IS_TRANSIENT(errno) ? 0 : -errno;
520
521 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
522
523 /* Now crank the state machine since we might be able to make progress after writing. For example,
524 * the server only processes "BEGIN" when the write buffer is empty.
525 */
526 return bus_socket_auth_verify(b);
527}
528
a7e3212d
LP
529static int bus_socket_read_auth(sd_bus *b) {
530 struct msghdr mh;
7f4e6a1c 531 struct iovec iov = {};
a7e3212d
LP
532 size_t n;
533 ssize_t k;
534 int r;
535 void *p;
fb29cdbe 536 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
15d5af81 537 bool handle_cmsg = false;
a7e3212d
LP
538
539 assert(b);
2181a7f5 540 assert(b->state == BUS_AUTHENTICATING);
a7e3212d
LP
541
542 r = bus_socket_auth_verify(b);
543 if (r != 0)
544 return r;
545
9607d947 546 n = MAX(256u, b->rbuffer_size * 2);
a7e3212d
LP
547
548 if (n > BUS_AUTH_SIZE_MAX)
549 n = BUS_AUTH_SIZE_MAX;
550
551 if (b->rbuffer_size >= n)
552 return -ENOBUFS;
553
554 p = realloc(b->rbuffer, n);
555 if (!p)
556 return -ENOMEM;
557
558 b->rbuffer = p;
559
5cfa2c3d 560 iov = IOVEC_MAKE((uint8_t *)b->rbuffer + b->rbuffer_size, n - b->rbuffer_size);
a7e3212d 561
c1093c34 562 if (b->prefer_readv) {
15d5af81 563 k = readv(b->input_fd, &iov, 1);
c1093c34
LP
564 if (k < 0)
565 k = -errno;
566 } else {
41ab8c67
LP
567 mh = (struct msghdr) {
568 .msg_iov = &iov,
569 .msg_iovlen = 1,
570 .msg_control = &control,
571 .msg_controllen = sizeof(control),
572 };
15d5af81 573
3691bcf3
LP
574 k = recvmsg_safe(b->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
575 if (k == -ENOTSOCK) {
15d5af81
LP
576 b->prefer_readv = true;
577 k = readv(b->input_fd, &iov, 1);
3691bcf3
LP
578 if (k < 0)
579 k = -errno;
15d5af81
LP
580 } else
581 handle_cmsg = true;
582 }
b3d06b92
YW
583 if (k < 0) {
584 if (ERRNO_IS_TRANSIENT(k))
585 return 0;
3691bcf3 586 return (int) k;
b3d06b92 587 }
3691bcf3
LP
588 if (k == 0) {
589 if (handle_cmsg)
590 cmsg_close_all(&mh); /* paranoia, we shouldn't have gotten any fds on EOF */
a7e3212d 591 return -ECONNRESET;
3691bcf3 592 }
a7e3212d
LP
593
594 b->rbuffer_size += k;
595
2a1288ff
LP
596 if (handle_cmsg) {
597 struct cmsghdr *cmsg;
598
599 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
600 if (cmsg->cmsg_level == SOL_SOCKET &&
601 cmsg->cmsg_type == SCM_RIGHTS) {
602 int j;
603
604 /* Whut? We received fds during the auth
605 * protocol? Somebody is playing games with
606 * us. Close them all, and fail */
607 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
608 close_many((int*) CMSG_DATA(cmsg), j);
609 return -EIO;
d868f2a3
ZJS
610 } else
611 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
612 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 613 }
2181a7f5 614
a7e3212d
LP
615 r = bus_socket_auth_verify(b);
616 if (r != 0)
617 return r;
618
619 return 1;
620}
621
8f04d2eb 622void bus_socket_setup(sd_bus *b) {
a7e3212d
LP
623 assert(b);
624
aec6d91f 625 /* Increase the buffers to 8 MB */
28e7e934 626 (void) fd_increase_rxbuf(b->input_fd, SNDBUF_SIZE);
6ae22ffb 627 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
a7e3212d 628
e1d337d4 629 b->message_version = 1;
0f437184 630 b->message_endian = 0;
8f04d2eb 631}
e1d337d4 632
8f04d2eb 633static void bus_get_peercred(sd_bus *b) {
c4e6556c
ZJS
634 int r;
635
8f04d2eb 636 assert(b);
18ac4643
LP
637 assert(!b->ucred_valid);
638 assert(!b->label);
f5fbe71d 639 assert(b->n_groups == SIZE_MAX);
8f04d2eb
LP
640
641 /* Get the peer for socketpair() sockets */
eff05270 642 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
c4e6556c
ZJS
643
644 /* Get the SELinux context of the peer */
db7d1dca 645 r = getpeersec(b->input_fd, &b->label);
18ac4643 646 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
db7d1dca 647 log_debug_errno(r, "Failed to determine peer security context: %m");
18ac4643
LP
648
649 /* Get the list of auxiliary groups of the peer */
650 r = getpeergroups(b->input_fd, &b->groups);
c599b325 651 if (r >= 0)
18ac4643 652 b->n_groups = (size_t) r;
c599b325
ZJS
653 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
654 log_debug_errno(r, "Failed to determine peer's group list: %m");
a7e3212d
LP
655}
656
2181a7f5 657static int bus_socket_start_auth_client(sd_bus *b) {
1ed4723d
DR
658 static const char sasl_auth_anonymous[] = {
659 /*
660 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
661 * message broker to aid debugging of clients. We fully anonymize the connection and use a
662 * static default.
663 */
347f4824
DR
664 /* HEX a n o n y m o u s */
665 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
1ed4723d
DR
666 };
667 static const char sasl_auth_external[] = {
668 "\0AUTH EXTERNAL\r\n"
669 "DATA\r\n"
670 };
671 static const char sasl_negotiate_unix_fd[] = {
672 "NEGOTIATE_UNIX_FD\r\n"
673 };
674 static const char sasl_begin[] = {
675 "BEGIN\r\n"
676 };
677 size_t i = 0;
a7e3212d
LP
678
679 assert(b);
680
1ed4723d
DR
681 if (b->anonymous_auth)
682 b->auth_iovec[i++] = IOVEC_MAKE((char*) sasl_auth_anonymous, sizeof(sasl_auth_anonymous) - 1);
683 else
684 b->auth_iovec[i++] = IOVEC_MAKE((char*) sasl_auth_external, sizeof(sasl_auth_external) - 1);
a7e3212d 685
c7db1984 686 if (b->accept_fd)
1ed4723d 687 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd);
a7e3212d 688
1ed4723d 689 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_begin);
a7e3212d
LP
690
691 return bus_socket_write_auth(b);
692}
693
a7893c6b 694int bus_socket_start_auth(sd_bus *b) {
2181a7f5
LP
695 assert(b);
696
8f04d2eb
LP
697 bus_get_peercred(b);
698
3e0e196e 699 bus_set_state(b, BUS_AUTHENTICATING);
036d61b3 700 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
2181a7f5 701
9ab32f9d 702 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 703 b->accept_fd = false;
2181a7f5 704
9ab32f9d
LP
705 if (b->output_fd != b->input_fd)
706 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 707 b->accept_fd = false;
e82c9509 708
2181a7f5
LP
709 if (b->is_server)
710 return bus_socket_read_auth(b);
711 else
712 return bus_socket_start_auth_client(b);
713}
714
8a5cd31e
LP
715static int bus_socket_inotify_setup(sd_bus *b) {
716 _cleanup_free_ int *new_watches = NULL;
717 _cleanup_free_ char *absolute = NULL;
319a4f4b 718 size_t n = 0, done = 0, i;
8a5cd31e
LP
719 unsigned max_follow = 32;
720 const char *p;
721 int wd, r;
722
723 assert(b);
724 assert(b->watch_bind);
725 assert(b->sockaddr.sa.sa_family == AF_UNIX);
726 assert(b->sockaddr.un.sun_path[0] != 0);
727
728 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
729 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
730 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
731 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
732 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
733 * components. */
734
735 if (b->inotify_fd < 0) {
736 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
737 if (b->inotify_fd < 0)
738 return -errno;
7fe2903c
LP
739
740 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
8a5cd31e
LP
741 }
742
743 /* Make sure the path is NUL terminated */
2f82562b
LP
744 p = strndupa_safe(b->sockaddr.un.sun_path,
745 sizeof(b->sockaddr.un.sun_path));
8a5cd31e
LP
746
747 /* Make sure the path is absolute */
748 r = path_make_absolute_cwd(p, &absolute);
749 if (r < 0)
750 goto fail;
751
752 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
753 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
754 * they are removed or renamed. */
755
319a4f4b 756 if (!GREEDY_REALLOC(new_watches, n + 1)) {
8a5cd31e
LP
757 r = -ENOMEM;
758 goto fail;
759 }
760
761 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
762 * always exists */
763 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
764 if (wd < 0) {
765 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
766 goto fail;
767 } else
768 new_watches[n++] = wd;
769
770 for (;;) {
771 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
772 size_t n_slashes, n_component;
773 char *c = NULL;
774
775 n_slashes = strspn(absolute + done, "/");
776 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
777
778 if (n_component == 0) /* The end */
779 break;
780
781 component = strndup(absolute + done, n_component);
782 if (!component) {
783 r = -ENOMEM;
784 goto fail;
785 }
786
787 /* A trailing slash? That's a directory, and not a socket then */
788 if (path_equal(component, "/")) {
789 r = -EISDIR;
790 goto fail;
791 }
792
793 /* A single dot? Let's eat this up */
794 if (path_equal(component, "/.")) {
795 done += n_component;
796 continue;
797 }
798
799 prefix = strndup(absolute, done + n_component);
800 if (!prefix) {
801 r = -ENOMEM;
802 goto fail;
803 }
804
319a4f4b 805 if (!GREEDY_REALLOC(new_watches, n + 1)) {
8a5cd31e
LP
806 r = -ENOMEM;
807 goto fail;
808 }
809
810 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
811 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
812
813 if (wd < 0) {
814 if (IN_SET(errno, ENOENT, ELOOP))
815 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
816
945403e6 817 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
8a5cd31e
LP
818 goto fail;
819 } else
820 new_watches[n++] = wd;
821
822 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
823 r = readlink_malloc(prefix, &destination);
824 if (r == -EINVAL) { /* not a symlink */
825 done += n_component;
826 continue;
827 }
828 if (r < 0)
829 goto fail;
830
831 if (isempty(destination)) { /* Empty symlink target? Yuck! */
832 r = -EINVAL;
833 goto fail;
834 }
835
836 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
837 r = -ELOOP;
838 goto fail;
839 }
840
841 if (path_is_absolute(destination)) {
842 /* For absolute symlinks we build the new path and start anew */
843 c = strjoin(destination, absolute + done + n_component);
844 done = 0;
845 } else {
846 _cleanup_free_ char *t = NULL;
847
848 /* For relative symlinks we replace the last component, and try again */
849 t = strndup(absolute, done);
850 if (!t)
851 return -ENOMEM;
852
853 c = strjoin(t, "/", destination, absolute + done + n_component);
854 }
855 if (!c) {
856 r = -ENOMEM;
857 goto fail;
858 }
859
860 free(absolute);
861 absolute = c;
862
863 max_follow--;
864 }
865
866 /* And now, let's remove all watches from the previous iteration we don't need anymore */
867 for (i = 0; i < b->n_inotify_watches; i++) {
868 bool found = false;
869 size_t j;
870
871 for (j = 0; j < n; j++)
872 if (new_watches[j] == b->inotify_watches[i]) {
873 found = true;
874 break;
875 }
876
877 if (found)
878 continue;
879
880 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
881 }
882
883 free_and_replace(b->inotify_watches, new_watches);
884 b->n_inotify_watches = n;
885
886 return 0;
887
888fail:
889 bus_close_inotify_fd(b);
890 return r;
891}
892
a7e3212d 893int bus_socket_connect(sd_bus *b) {
8a5cd31e 894 bool inotify_done = false;
a7e3212d
LP
895 int r;
896
897 assert(b);
a7e3212d 898
8a5cd31e
LP
899 for (;;) {
900 assert(b->input_fd < 0);
901 assert(b->output_fd < 0);
902 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
a7e3212d 903
165fee86
ZJS
904 if (DEBUG_LOGGING) {
905 _cleanup_free_ char *pretty = NULL;
906 (void) sockaddr_pretty(&b->sockaddr.sa, b->sockaddr_size, false, true, &pretty);
907 log_debug("sd-bus: starting bus%s%s by connecting to %s...",
908 b->description ? " " : "", strempty(b->description), strnull(pretty));
909 }
910
8a5cd31e
LP
911 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
912 if (b->input_fd < 0)
913 return -errno;
e82c9509 914
7fe2903c
LP
915 b->input_fd = fd_move_above_stdio(b->input_fd);
916
8a5cd31e
LP
917 b->output_fd = b->input_fd;
918 bus_socket_setup(b);
a7e3212d 919
8a5cd31e
LP
920 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
921 if (errno == EINPROGRESS) {
a7e3212d 922
8a5cd31e
LP
923 /* If we have any inotify watches open, close them now, we don't need them anymore, as
924 * we have successfully initiated a connection */
925 bus_close_inotify_fd(b);
926
927 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
928 * we start parsing the address string. The only reason we set the state explicitly
929 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
3e0e196e 930 bus_set_state(b, BUS_OPENING);
8a5cd31e
LP
931 return 1;
932 }
933
934 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
935 b->watch_bind &&
936 b->sockaddr.sa.sa_family == AF_UNIX &&
937 b->sockaddr.un.sun_path[0] != 0) {
938
939 /* This connection attempt failed, let's release the socket for now, and start with a
940 * fresh one when reconnecting. */
941 bus_close_io_fds(b);
942
943 if (inotify_done) {
944 /* inotify set up already, don't do it again, just return now, and remember
945 * that we are waiting for inotify events now. */
3e0e196e 946 bus_set_state(b, BUS_WATCH_BIND);
8a5cd31e
LP
947 return 1;
948 }
949
950 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
951 r = bus_socket_inotify_setup(b);
952 if (r < 0)
953 return r;
954
955 /* Let's now try to connect a second time, because in theory there's otherwise a race
956 * here: the socket might have been created in the time between our first connect() and
957 * the time we set up the inotify logic. But let's remember that we set up inotify now,
958 * so that we don't do the connect() more than twice. */
959 inotify_done = true;
960
961 } else
962 return -errno;
963 } else
964 break;
a7e3212d
LP
965 }
966
8a5cd31e
LP
967 /* Yay, established, we don't need no inotify anymore! */
968 bus_close_inotify_fd(b);
969
a7e3212d
LP
970 return bus_socket_start_auth(b);
971}
972
973int bus_socket_exec(sd_bus *b) {
e82c9509 974 int s[2], r;
a7e3212d
LP
975
976 assert(b);
e82c9509
LP
977 assert(b->input_fd < 0);
978 assert(b->output_fd < 0);
a7e3212d 979 assert(b->exec_path);
392cf1d0 980 assert(b->busexec_pid == 0);
a7e3212d 981
87fa2e21
ZJS
982 if (DEBUG_LOGGING) {
983 _cleanup_free_ char *line = NULL;
984
985 if (b->exec_argv)
4ef15008 986 line = quote_command_line(b->exec_argv, SHELL_ESCAPE_EMPTY);
87fa2e21
ZJS
987
988 log_debug("sd-bus: starting bus%s%s with %s%s",
989 b->description ? " " : "", strempty(b->description),
990 line ?: b->exec_path,
991 b->exec_argv && !line ? "…" : "");
992 }
165fee86 993
e82c9509
LP
994 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
995 if (r < 0)
a7e3212d
LP
996 return -errno;
997
392cf1d0 998 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &b->busexec_pid);
4c253ed1 999 if (r < 0) {
3d94f76c 1000 safe_close_pair(s);
4c253ed1 1001 return r;
a7e3212d 1002 }
4c253ed1 1003 if (r == 0) {
a7e3212d
LP
1004 /* Child */
1005
aedec452
LP
1006 r = rearrange_stdio(s[1], s[1], STDERR_FILENO);
1007 TAKE_FD(s[1]);
1008 if (r < 0)
2b33ab09 1009 _exit(EXIT_FAILURE);
a7e3212d 1010
595225af
LP
1011 (void) rlimit_nofile_safe();
1012
a7e3212d
LP
1013 if (b->exec_argv)
1014 execvp(b->exec_path, b->exec_argv);
87fa2e21
ZJS
1015 else
1016 execvp(b->exec_path, STRV_MAKE(b->exec_path));
a7e3212d
LP
1017
1018 _exit(EXIT_FAILURE);
1019 }
1020
03e334a1 1021 safe_close(s[1]);
7fe2903c 1022 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
a7e3212d 1023
8f04d2eb 1024 bus_socket_setup(b);
e1d337d4 1025
a7e3212d
LP
1026 return bus_socket_start_auth(b);
1027}
1028
1029int bus_socket_take_fd(sd_bus *b) {
a7e3212d
LP
1030 assert(b);
1031
8f04d2eb 1032 bus_socket_setup(b);
a7e3212d
LP
1033
1034 return bus_socket_start_auth(b);
1035}
1036
1037int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
a7e3212d
LP
1038 struct iovec *iov;
1039 ssize_t k;
1040 size_t n;
1041 unsigned j;
bc7fd8cd 1042 int r;
a7e3212d
LP
1043
1044 assert(bus);
1045 assert(m);
1046 assert(idx);
945c2931 1047 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1048
6629161f 1049 if (*idx >= BUS_MESSAGE_SIZE(m))
a7e3212d 1050 return 0;
a7e3212d 1051
bc7fd8cd
LP
1052 r = bus_message_setup_iovec(m);
1053 if (r < 0)
1054 return r;
2100fa10 1055
a7e3212d 1056 n = m->n_iovec * sizeof(struct iovec);
6e9417f5 1057 iov = newa(struct iovec, n);
75f32f04 1058 memcpy_safe(iov, m->iovec, n);
a7e3212d
LP
1059
1060 j = 0;
1061 iovec_advance(iov, &j, *idx);
1062
15d5af81
LP
1063 if (bus->prefer_writev)
1064 k = writev(bus->output_fd, iov, m->n_iovec);
1065 else {
7f4e6a1c
ZJS
1066 struct msghdr mh = {
1067 .msg_iov = iov,
1068 .msg_iovlen = m->n_iovec,
1069 };
15d5af81 1070
f29eef2e 1071 if (m->n_fds > 0 && *idx == 0) {
15d5af81 1072 struct cmsghdr *control;
15d5af81 1073
a258f491
LP
1074 mh.msg_controllen = CMSG_SPACE(sizeof(int) * m->n_fds);
1075 mh.msg_control = alloca0(mh.msg_controllen);
1076 control = CMSG_FIRSTHDR(&mh);
1077 control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
15d5af81
LP
1078 control->cmsg_level = SOL_SOCKET;
1079 control->cmsg_type = SCM_RIGHTS;
15d5af81
LP
1080 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1081 }
1082
15d5af81
LP
1083 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1084 if (k < 0 && errno == ENOTSOCK) {
1085 bus->prefer_writev = true;
1086 k = writev(bus->output_fd, iov, m->n_iovec);
1087 }
1088 }
a7e3212d 1089
a7e3212d 1090 if (k < 0)
b3d06b92 1091 return ERRNO_IS_TRANSIENT(errno) ? 0 : -errno;
a7e3212d
LP
1092
1093 *idx += (size_t) k;
1094 return 1;
1095}
1096
1097static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1098 uint32_t a, b;
1099 uint8_t e;
1100 uint64_t sum;
1101
1102 assert(bus);
1103 assert(need);
945c2931 1104 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1105
1106 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1107 *need = sizeof(struct bus_header) + 8;
1108
1109 /* Minimum message size:
1110 *
1111 * Header +
1112 *
1113 * Method Call: +2 string headers
1114 * Signal: +3 string headers
1115 * Method Error: +1 string headers
1116 * +1 uint32 headers
1117 * Method Reply: +1 uint32 headers
1118 *
1119 * A string header is at least 9 bytes
1120 * A uint32 header is at least 8 bytes
1121 *
1122 * Hence the minimum message size of a valid message
1123 * is header + 8 bytes */
1124
1125 return 0;
1126 }
1127
1128 a = ((const uint32_t*) bus->rbuffer)[1];
1129 b = ((const uint32_t*) bus->rbuffer)[3];
1130
1131 e = ((const uint8_t*) bus->rbuffer)[0];
0461f8cd 1132 if (e == BUS_LITTLE_ENDIAN) {
a7e3212d
LP
1133 a = le32toh(a);
1134 b = le32toh(b);
0461f8cd 1135 } else if (e == BUS_BIG_ENDIAN) {
a7e3212d
LP
1136 a = be32toh(a);
1137 b = be32toh(b);
1138 } else
1139 return -EBADMSG;
1140
dc7be332 1141 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN8(b) + (uint64_t) a;
a7e3212d
LP
1142 if (sum >= BUS_MESSAGE_SIZE_MAX)
1143 return -ENOBUFS;
1144
1145 *need = (size_t) sum;
1146 return 0;
1147}
1148
7d22c717 1149static int bus_socket_make_message(sd_bus *bus, size_t size) {
6d586a13 1150 sd_bus_message *t = NULL;
a7e3212d
LP
1151 void *b;
1152 int r;
1153
1154 assert(bus);
a7e3212d 1155 assert(bus->rbuffer_size >= size);
945c2931 1156 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1157
7adc46fc
LP
1158 r = bus_rqueue_make_room(bus);
1159 if (r < 0)
1160 return r;
1161
a7e3212d
LP
1162 if (bus->rbuffer_size > size) {
1163 b = memdup((const uint8_t*) bus->rbuffer + size,
1164 bus->rbuffer_size - size);
1165 if (!b)
1166 return -ENOMEM;
1167 } else
1168 b = NULL;
1169
df2d202e
LP
1170 r = bus_message_from_malloc(bus,
1171 bus->rbuffer, size,
a7e3212d 1172 bus->fds, bus->n_fds,
038f9863 1173 NULL,
a7e3212d 1174 &t);
3dec5201 1175 if (r == -EBADMSG) {
6d586a13 1176 log_debug_errno(r, "Received invalid message from connection %s, dropping.", strna(bus->description));
3dec5201
ZJS
1177 free(bus->rbuffer); /* We want to drop current rbuffer and proceed with whatever remains in b */
1178 } else if (r < 0) {
a7e3212d
LP
1179 free(b);
1180 return r;
1181 }
1182
3dec5201 1183 /* rbuffer ownership was either transferred to t, or we got EBADMSG and dropped it. */
a7e3212d
LP
1184 bus->rbuffer = b;
1185 bus->rbuffer_size -= size;
1186
1187 bus->fds = NULL;
1188 bus->n_fds = 0;
1189
c1757a70 1190 if (t) {
f1617a3b 1191 t->read_counter = ++bus->read_counter;
c1757a70
LP
1192 bus->rqueue[bus->rqueue_size++] = bus_message_ref_queued(t, bus);
1193 sd_bus_message_unref(t);
1194 }
7d22c717 1195
a7e3212d
LP
1196 return 1;
1197}
1198
7d22c717 1199int bus_socket_read_message(sd_bus *bus) {
a7e3212d 1200 struct msghdr mh;
7f4e6a1c 1201 struct iovec iov = {};
a7e3212d
LP
1202 ssize_t k;
1203 size_t need;
1204 int r;
1205 void *b;
fb29cdbe 1206 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)) control;
4d3a5b10 1207 bool handle_cmsg = false;
a7e3212d
LP
1208
1209 assert(bus);
945c2931 1210 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1211
1212 r = bus_socket_read_message_need(bus, &need);
1213 if (r < 0)
1214 return r;
1215
1216 if (bus->rbuffer_size >= need)
7d22c717 1217 return bus_socket_make_message(bus, need);
a7e3212d
LP
1218
1219 b = realloc(bus->rbuffer, need);
1220 if (!b)
1221 return -ENOMEM;
1222
1223 bus->rbuffer = b;
1224
5cfa2c3d 1225 iov = IOVEC_MAKE((uint8_t *)bus->rbuffer + bus->rbuffer_size, need - bus->rbuffer_size);
a7e3212d 1226
c1093c34 1227 if (bus->prefer_readv) {
15d5af81 1228 k = readv(bus->input_fd, &iov, 1);
c1093c34
LP
1229 if (k < 0)
1230 k = -errno;
1231 } else {
41ab8c67
LP
1232 mh = (struct msghdr) {
1233 .msg_iov = &iov,
1234 .msg_iovlen = 1,
1235 .msg_control = &control,
1236 .msg_controllen = sizeof(control),
1237 };
15d5af81 1238
3691bcf3
LP
1239 k = recvmsg_safe(bus->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1240 if (k == -ENOTSOCK) {
15d5af81
LP
1241 bus->prefer_readv = true;
1242 k = readv(bus->input_fd, &iov, 1);
3691bcf3
LP
1243 if (k < 0)
1244 k = -errno;
15d5af81
LP
1245 } else
1246 handle_cmsg = true;
1247 }
b3d06b92
YW
1248 if (k < 0) {
1249 if (ERRNO_IS_TRANSIENT(k))
1250 return 0;
3691bcf3 1251 return (int) k;
b3d06b92 1252 }
3691bcf3
LP
1253 if (k == 0) {
1254 if (handle_cmsg)
1255 cmsg_close_all(&mh); /* On EOF we shouldn't have gotten an fd, but let's make sure */
a7e3212d 1256 return -ECONNRESET;
3691bcf3 1257 }
a7e3212d
LP
1258
1259 bus->rbuffer_size += k;
1260
2a1288ff
LP
1261 if (handle_cmsg) {
1262 struct cmsghdr *cmsg;
1263
1264 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
1265 if (cmsg->cmsg_level == SOL_SOCKET &&
1266 cmsg->cmsg_type == SCM_RIGHTS) {
7fe2903c 1267 int n, *f, i;
15d5af81
LP
1268
1269 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1270
1271 if (!bus->can_fds) {
1272 /* Whut? We received fds but this
1273 * isn't actually enabled? Close them,
1274 * and fail */
1275
1276 close_many((int*) CMSG_DATA(cmsg), n);
1277 return -EIO;
1278 }
1279
62d74c78 1280 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
15d5af81
LP
1281 if (!f) {
1282 close_many((int*) CMSG_DATA(cmsg), n);
1283 return -ENOMEM;
1284 }
1285
7fe2903c
LP
1286 for (i = 0; i < n; i++)
1287 f[bus->n_fds++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg))[i]);
15d5af81 1288 bus->fds = f;
d868f2a3
ZJS
1289 } else
1290 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1291 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 1292 }
a7e3212d
LP
1293
1294 r = bus_socket_read_message_need(bus, &need);
1295 if (r < 0)
1296 return r;
1297
1298 if (bus->rbuffer_size >= need)
7d22c717 1299 return bus_socket_make_message(bus, need);
a7e3212d
LP
1300
1301 return 1;
1302}
1303
1304int bus_socket_process_opening(sd_bus *b) {
0f2d351f 1305 int error = 0, events, r;
a7e3212d 1306 socklen_t slen = sizeof(error);
a7e3212d 1307
a7e3212d
LP
1308 assert(b->state == BUS_OPENING);
1309
0f2d351f
LP
1310 events = fd_wait_for_event(b->output_fd, POLLOUT, 0);
1311 if (events < 0)
1312 return events;
1313 if (!(events & (POLLOUT|POLLERR|POLLHUP)))
a7e3212d
LP
1314 return 0;
1315
e82c9509 1316 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
a7e3212d
LP
1317 if (r < 0)
1318 b->last_connect_error = errno;
1319 else if (error != 0)
1320 b->last_connect_error = error;
0f2d351f 1321 else if (events & (POLLERR|POLLHUP))
a7e3212d
LP
1322 b->last_connect_error = ECONNREFUSED;
1323 else
1324 return bus_socket_start_auth(b);
1325
1326 return bus_next_address(b);
1327}
1328
1329int bus_socket_process_authenticating(sd_bus *b) {
1330 int r;
1331
1332 assert(b);
1333 assert(b->state == BUS_AUTHENTICATING);
1334
1335 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1336 return -ETIMEDOUT;
1337
1338 r = bus_socket_write_auth(b);
1339 if (r != 0)
1340 return r;
1341
1342 return bus_socket_read_auth(b);
1343}
8a5cd31e
LP
1344
1345int bus_socket_process_watch_bind(sd_bus *b) {
1346 int r, q;
1347
1348 assert(b);
1349 assert(b->state == BUS_WATCH_BIND);
1350 assert(b->inotify_fd >= 0);
1351
1352 r = flush_fd(b->inotify_fd);
1353 if (r <= 0)
1354 return r;
1355
1356 log_debug("Got inotify event on bus %s.", strna(b->description));
1357
1358 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1359 * to it again */
1360
1361 r = bus_socket_connect(b);
1362 if (r < 0)
1363 return r;
1364
1365 q = bus_attach_io_events(b);
1366 if (q < 0)
1367 return q;
1368
1369 q = bus_attach_inotify_event(b);
1370 if (q < 0)
1371 return q;
1372
1373 return r;
1374}