]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/libsystemd/sd-bus/bus-socket.c
process-util: rename FORK_NULL_STDIO -> FORK_REARRANGE_STDIO
[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"
24882e06 25#include "signal-util.h"
15a5e950 26#include "stdio-util.h"
07630cea 27#include "string-util.h"
b1d4f8e1 28#include "user-util.h"
07630cea 29#include "utf8.h"
a7e3212d 30
aec6d91f
LP
31#define SNDBUF_SIZE (8*1024*1024)
32
2181a7f5 33static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
a7e3212d
LP
34
35 while (size > 0) {
36 struct iovec *i = iov + *idx;
37
38 if (i->iov_len > size) {
39 i->iov_base = (uint8_t*) i->iov_base + size;
40 i->iov_len -= size;
41 return;
42 }
43
44 size -= i->iov_len;
45
5cfa2c3d 46 *i = IOVEC_MAKE(NULL, 0);
a7e3212d 47
313cefa1 48 (*idx)++;
a7e3212d
LP
49 }
50}
51
bc7fd8cd 52static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
2100fa10
LP
53 assert(m);
54 assert(p);
55 assert(sz > 0);
56
5cfa2c3d 57 m->iovec[m->n_iovec++] = IOVEC_MAKE((void*) p, sz);
bc7fd8cd
LP
58
59 return 0;
2100fa10
LP
60}
61
bc7fd8cd
LP
62static int bus_message_setup_iovec(sd_bus_message *m) {
63 struct bus_body_part *part;
13c299d3 64 unsigned n, i;
bc7fd8cd
LP
65 int r;
66
2100fa10
LP
67 assert(m);
68 assert(m->sealed);
69
70 if (m->n_iovec > 0)
bc7fd8cd
LP
71 return 0;
72
73 assert(!m->iovec);
2100fa10 74
c91cb83c 75 n = 1 + m->n_body_parts;
bc7fd8cd
LP
76 if (n < ELEMENTSOF(m->iovec_fixed))
77 m->iovec = m->iovec_fixed;
78 else {
79 m->iovec = new(struct iovec, n);
66b26c5c
LP
80 if (!m->iovec) {
81 r = -ENOMEM;
82 goto fail;
83 }
bc7fd8cd 84 }
2100fa10 85
c91cb83c 86 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
bc7fd8cd 87 if (r < 0)
66b26c5c 88 goto fail;
2100fa10 89
9b29bb68 90 MESSAGE_FOREACH_PART(part, i, m) {
66b26c5c
LP
91 r = bus_body_part_map(part);
92 if (r < 0)
93 goto fail;
94
bc7fd8cd
LP
95 r = append_iovec(m, part->data, part->size);
96 if (r < 0)
66b26c5c 97 goto fail;
bc7fd8cd
LP
98 }
99
100 assert(n == m->n_iovec);
101
102 return 0;
66b26c5c
LP
103
104fail:
105 m->poisoned = true;
106 return r;
2100fa10
LP
107}
108
2181a7f5
LP
109bool bus_socket_auth_needs_write(sd_bus *b) {
110
111 unsigned i;
112
113 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
114 return false;
115
116 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
117 struct iovec *j = b->auth_iovec + i;
118
119 if (j->iov_len > 0)
120 return true;
121 }
122
123 return false;
124}
125
2181a7f5 126static int bus_socket_auth_verify_client(sd_bus *b) {
347f4824 127 char *l, *lines[4] = {};
a7e3212d 128 sd_id128_t peer;
347f4824 129 size_t i, n;
a7e3212d
LP
130 int r;
131
2181a7f5
LP
132 assert(b);
133
1ed4723d 134 /*
347f4824
DR
135 * We expect up to three response lines:
136 * "DATA\r\n" (optional)
1ed4723d
DR
137 * "OK <server-id>\r\n"
138 * "AGREE_UNIX_FD\r\n" (optional)
139 */
a7e3212d 140
347f4824
DR
141 n = 0;
142 lines[n] = b->rbuffer;
143 for (i = 0; i < 3; ++i) {
144 l = memmem_safe(lines[n], b->rbuffer_size - (lines[n] - (char*) b->rbuffer), "\r\n", 2);
145 if (l)
146 lines[++n] = l + 2;
147 else
148 break;
a7e3212d
LP
149 }
150
347f4824
DR
151 /*
152 * If we sent a non-empty initial response, then we just expect an OK
153 * reply. We currently do this if, and only if, we picked ANONYMOUS.
154 * If we did not send an initial response, then we expect a DATA
155 * challenge, reply with our own DATA, and expect an OK reply. We do
156 * this for EXTERNAL.
157 * If FD negotiation was requested, we additionally expect
158 * an AGREE_UNIX_FD response in all cases.
159 */
160 if (n < (b->anonymous_auth ? 1U : 2U) + !!b->accept_fd)
161 return 0; /* wait for more data */
162
163 i = 0;
164
165 /* In case of EXTERNAL, verify the first response was DATA. */
166 if (!b->anonymous_auth) {
167 l = lines[i++];
168 if (lines[i] - l == 4 + 2) {
169 if (memcmp(l, "DATA", 4))
170 return -EPERM;
171 } else if (lines[i] - l == 3 + 32 + 2) {
172 /*
173 * Old versions of the server-side implementation of
174 * `sd-bus` replied with "OK <id>" to "AUTH" requests
175 * from a client, even if the "AUTH" line did not
176 * contain inlined arguments. Therefore, we also accept
177 * "OK <id>" here, even though it is technically the
178 * wrong reply. We ignore the "<id>" parameter, though,
179 * since it has no real value.
180 */
181 if (memcmp(l, "OK ", 3))
182 return -EPERM;
183 } else
1ed4723d 184 return -EPERM;
347f4824 185 }
a7e3212d 186
1ed4723d 187 /* Now check the OK line. */
347f4824 188 l = lines[i++];
1ed4723d 189
347f4824 190 if (lines[i] - l != 3 + 32 + 2)
a7e3212d 191 return -EPERM;
347f4824 192 if (memcmp(l, "OK ", 3))
a7e3212d
LP
193 return -EPERM;
194
2181a7f5
LP
195 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
196
347f4824 197 for (unsigned j = 0; j < 32; j += 2) {
a7e3212d
LP
198 int x, y;
199
347f4824
DR
200 x = unhexchar(l[3 + j]);
201 y = unhexchar(l[3 + j + 1]);
a7e3212d
LP
202
203 if (x < 0 || y < 0)
204 return -EINVAL;
205
347f4824 206 peer.bytes[j/2] = ((uint8_t) x << 4 | (uint8_t) y);
a7e3212d
LP
207 }
208
3bbaff3e 209 if (!sd_id128_is_null(b->server_id) &&
98178d39 210 !sd_id128_equal(b->server_id, peer))
a7e3212d
LP
211 return -EPERM;
212
98178d39 213 b->server_id = peer;
a7e3212d 214
1ed4723d 215 /* And possibly check the third line, too */
347f4824
DR
216 if (b->accept_fd) {
217 l = lines[i++];
218 b->can_fds = !!memory_startswith(l, lines[i] - l, "AGREE_UNIX_FD");
219 }
a7e3212d 220
347f4824 221 assert(i == n);
a7e3212d 222
347f4824
DR
223 b->rbuffer_size -= (lines[i] - (char*) b->rbuffer);
224 memmove(b->rbuffer, lines[i], b->rbuffer_size);
a7e3212d
LP
225
226 r = bus_start_running(b);
227 if (r < 0)
228 return r;
229
230 return 1;
231}
232
2181a7f5
LP
233static bool line_equals(const char *s, size_t m, const char *line) {
234 size_t l;
235
236 l = strlen(line);
237 if (l != m)
238 return false;
239
240 return memcmp(s, line, l) == 0;
241}
242
243static bool line_begins(const char *s, size_t m, const char *word) {
d27b725a 244 const char *p;
2181a7f5 245
d27b725a 246 p = memory_startswith(s, m, word);
3f10c662 247 return p && (p == (s + m) || *p == ' ');
2181a7f5
LP
248}
249
250static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
251 _cleanup_free_ char *token = NULL;
30494563
TG
252 size_t len;
253 int r;
2181a7f5
LP
254
255 if (!b->anonymous_auth)
256 return 0;
257
258 if (l <= 0)
259 return 1;
260
261 assert(p[0] == ' ');
262 p++; l--;
263
264 if (l % 2 != 0)
265 return 0;
2181a7f5 266
30494563
TG
267 r = unhexmem(p, l, (void **) &token, &len);
268 if (r < 0)
269 return 0;
270
271 if (memchr(token, 0, len))
2181a7f5
LP
272 return 0;
273
274 return !!utf8_is_valid(token);
275}
276
277static int verify_external_token(sd_bus *b, const char *p, size_t l) {
278 _cleanup_free_ char *token = NULL;
30494563 279 size_t len;
2181a7f5
LP
280 uid_t u;
281 int r;
282
b3d06b92 283 /* We don't do any real authentication here. Instead, if
be7148eb 284 * the owner of this bus wanted authentication they should have
2181a7f5
LP
285 * checked SO_PEERCRED before even creating the bus object. */
286
8411d2a2 287 if (!b->anonymous_auth && !b->ucred_valid)
2181a7f5
LP
288 return 0;
289
290 if (l <= 0)
291 return 1;
292
293 assert(p[0] == ' ');
294 p++; l--;
295
296 if (l % 2 != 0)
297 return 0;
298
30494563
TG
299 r = unhexmem(p, l, (void**) &token, &len);
300 if (r < 0)
301 return 0;
2181a7f5 302
30494563 303 if (memchr(token, 0, len))
2181a7f5
LP
304 return 0;
305
306 r = parse_uid(token, &u);
307 if (r < 0)
308 return 0;
309
8411d2a2
LP
310 /* We ignore the passed value if anonymous authentication is
311 * on anyway. */
312 if (!b->anonymous_auth && u != b->ucred.uid)
2181a7f5
LP
313 return 0;
314
315 return 1;
316}
317
318static int bus_socket_auth_write(sd_bus *b, const char *t) {
319 char *p;
320 size_t l;
321
322 assert(b);
323 assert(t);
324
325 /* We only make use of the first iovec */
945c2931 326 assert(IN_SET(b->auth_index, 0, 1));
2181a7f5
LP
327
328 l = strlen(t);
329 p = malloc(b->auth_iovec[0].iov_len + l);
330 if (!p)
331 return -ENOMEM;
332
75f32f04 333 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
2181a7f5
LP
334 memcpy(p + b->auth_iovec[0].iov_len, t, l);
335
336 b->auth_iovec[0].iov_base = p;
337 b->auth_iovec[0].iov_len += l;
338
339 free(b->auth_buffer);
340 b->auth_buffer = p;
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);
607 close_many((int*) CMSG_DATA(cmsg), j);
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");
a7e3212d
LP
654}
655
2181a7f5 656static int bus_socket_start_auth_client(sd_bus *b) {
1ed4723d
DR
657 static const char sasl_auth_anonymous[] = {
658 /*
659 * We use an arbitrary trace-string for the ANONYMOUS authentication. It can be used by the
660 * message broker to aid debugging of clients. We fully anonymize the connection and use a
661 * static default.
662 */
347f4824
DR
663 /* HEX a n o n y m o u s */
664 "\0AUTH ANONYMOUS 616e6f6e796d6f7573\r\n"
1ed4723d
DR
665 };
666 static const char sasl_auth_external[] = {
667 "\0AUTH EXTERNAL\r\n"
668 "DATA\r\n"
669 };
670 static const char sasl_negotiate_unix_fd[] = {
671 "NEGOTIATE_UNIX_FD\r\n"
672 };
673 static const char sasl_begin[] = {
674 "BEGIN\r\n"
675 };
676 size_t i = 0;
a7e3212d
LP
677
678 assert(b);
679
1ed4723d
DR
680 if (b->anonymous_auth)
681 b->auth_iovec[i++] = IOVEC_MAKE((char*) sasl_auth_anonymous, sizeof(sasl_auth_anonymous) - 1);
682 else
683 b->auth_iovec[i++] = IOVEC_MAKE((char*) sasl_auth_external, sizeof(sasl_auth_external) - 1);
a7e3212d 684
c7db1984 685 if (b->accept_fd)
1ed4723d 686 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_negotiate_unix_fd);
a7e3212d 687
1ed4723d 688 b->auth_iovec[i++] = IOVEC_MAKE_STRING(sasl_begin);
a7e3212d
LP
689
690 return bus_socket_write_auth(b);
691}
692
a7893c6b 693int bus_socket_start_auth(sd_bus *b) {
2181a7f5
LP
694 assert(b);
695
8f04d2eb
LP
696 bus_get_peercred(b);
697
3e0e196e 698 bus_set_state(b, BUS_AUTHENTICATING);
036d61b3 699 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
2181a7f5 700
9ab32f9d 701 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 702 b->accept_fd = false;
2181a7f5 703
9ab32f9d
LP
704 if (b->output_fd != b->input_fd)
705 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 706 b->accept_fd = false;
e82c9509 707
2181a7f5
LP
708 if (b->is_server)
709 return bus_socket_read_auth(b);
710 else
711 return bus_socket_start_auth_client(b);
712}
713
8a5cd31e
LP
714static int bus_socket_inotify_setup(sd_bus *b) {
715 _cleanup_free_ int *new_watches = NULL;
716 _cleanup_free_ char *absolute = NULL;
319a4f4b 717 size_t n = 0, done = 0, i;
8a5cd31e
LP
718 unsigned max_follow = 32;
719 const char *p;
720 int wd, r;
721
722 assert(b);
723 assert(b->watch_bind);
724 assert(b->sockaddr.sa.sa_family == AF_UNIX);
725 assert(b->sockaddr.un.sun_path[0] != 0);
726
727 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
728 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
729 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
730 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
731 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
732 * components. */
733
734 if (b->inotify_fd < 0) {
735 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
736 if (b->inotify_fd < 0)
737 return -errno;
7fe2903c
LP
738
739 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
8a5cd31e
LP
740 }
741
742 /* Make sure the path is NUL terminated */
2f82562b
LP
743 p = strndupa_safe(b->sockaddr.un.sun_path,
744 sizeof(b->sockaddr.un.sun_path));
8a5cd31e
LP
745
746 /* Make sure the path is absolute */
747 r = path_make_absolute_cwd(p, &absolute);
748 if (r < 0)
749 goto fail;
750
751 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
752 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
753 * they are removed or renamed. */
754
319a4f4b 755 if (!GREEDY_REALLOC(new_watches, n + 1)) {
8a5cd31e
LP
756 r = -ENOMEM;
757 goto fail;
758 }
759
760 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
761 * always exists */
762 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
763 if (wd < 0) {
764 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
765 goto fail;
766 } else
767 new_watches[n++] = wd;
768
769 for (;;) {
770 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
771 size_t n_slashes, n_component;
772 char *c = NULL;
773
774 n_slashes = strspn(absolute + done, "/");
775 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
776
777 if (n_component == 0) /* The end */
778 break;
779
780 component = strndup(absolute + done, n_component);
781 if (!component) {
782 r = -ENOMEM;
783 goto fail;
784 }
785
786 /* A trailing slash? That's a directory, and not a socket then */
787 if (path_equal(component, "/")) {
788 r = -EISDIR;
789 goto fail;
790 }
791
792 /* A single dot? Let's eat this up */
793 if (path_equal(component, "/.")) {
794 done += n_component;
795 continue;
796 }
797
798 prefix = strndup(absolute, done + n_component);
799 if (!prefix) {
800 r = -ENOMEM;
801 goto fail;
802 }
803
319a4f4b 804 if (!GREEDY_REALLOC(new_watches, n + 1)) {
8a5cd31e
LP
805 r = -ENOMEM;
806 goto fail;
807 }
808
809 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
810 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
811
812 if (wd < 0) {
813 if (IN_SET(errno, ENOENT, ELOOP))
814 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
815
945403e6 816 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
8a5cd31e
LP
817 goto fail;
818 } else
819 new_watches[n++] = wd;
820
821 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
822 r = readlink_malloc(prefix, &destination);
823 if (r == -EINVAL) { /* not a symlink */
824 done += n_component;
825 continue;
826 }
827 if (r < 0)
828 goto fail;
829
830 if (isempty(destination)) { /* Empty symlink target? Yuck! */
831 r = -EINVAL;
832 goto fail;
833 }
834
835 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
836 r = -ELOOP;
837 goto fail;
838 }
839
840 if (path_is_absolute(destination)) {
841 /* For absolute symlinks we build the new path and start anew */
842 c = strjoin(destination, absolute + done + n_component);
843 done = 0;
844 } else {
845 _cleanup_free_ char *t = NULL;
846
847 /* For relative symlinks we replace the last component, and try again */
848 t = strndup(absolute, done);
849 if (!t)
850 return -ENOMEM;
851
852 c = strjoin(t, "/", destination, absolute + done + n_component);
853 }
854 if (!c) {
855 r = -ENOMEM;
856 goto fail;
857 }
858
859 free(absolute);
860 absolute = c;
861
862 max_follow--;
863 }
864
865 /* And now, let's remove all watches from the previous iteration we don't need anymore */
866 for (i = 0; i < b->n_inotify_watches; i++) {
867 bool found = false;
868 size_t j;
869
870 for (j = 0; j < n; j++)
871 if (new_watches[j] == b->inotify_watches[i]) {
872 found = true;
873 break;
874 }
875
876 if (found)
877 continue;
878
879 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
880 }
881
882 free_and_replace(b->inotify_watches, new_watches);
883 b->n_inotify_watches = n;
884
885 return 0;
886
887fail:
888 bus_close_inotify_fd(b);
889 return r;
890}
891
a7e3212d 892int bus_socket_connect(sd_bus *b) {
8a5cd31e 893 bool inotify_done = false;
a7e3212d
LP
894 int r;
895
896 assert(b);
a7e3212d 897
8a5cd31e
LP
898 for (;;) {
899 assert(b->input_fd < 0);
900 assert(b->output_fd < 0);
901 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
a7e3212d 902
165fee86
ZJS
903 if (DEBUG_LOGGING) {
904 _cleanup_free_ char *pretty = NULL;
905 (void) sockaddr_pretty(&b->sockaddr.sa, b->sockaddr_size, false, true, &pretty);
906 log_debug("sd-bus: starting bus%s%s by connecting to %s...",
907 b->description ? " " : "", strempty(b->description), strnull(pretty));
908 }
909
8a5cd31e
LP
910 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
911 if (b->input_fd < 0)
912 return -errno;
e82c9509 913
7fe2903c
LP
914 b->input_fd = fd_move_above_stdio(b->input_fd);
915
8a5cd31e
LP
916 b->output_fd = b->input_fd;
917 bus_socket_setup(b);
a7e3212d 918
8a5cd31e
LP
919 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
920 if (errno == EINPROGRESS) {
a7e3212d 921
8a5cd31e
LP
922 /* If we have any inotify watches open, close them now, we don't need them anymore, as
923 * we have successfully initiated a connection */
924 bus_close_inotify_fd(b);
925
926 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
927 * we start parsing the address string. The only reason we set the state explicitly
928 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
3e0e196e 929 bus_set_state(b, BUS_OPENING);
8a5cd31e
LP
930 return 1;
931 }
932
933 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
934 b->watch_bind &&
935 b->sockaddr.sa.sa_family == AF_UNIX &&
936 b->sockaddr.un.sun_path[0] != 0) {
937
938 /* This connection attempt failed, let's release the socket for now, and start with a
939 * fresh one when reconnecting. */
940 bus_close_io_fds(b);
941
942 if (inotify_done) {
943 /* inotify set up already, don't do it again, just return now, and remember
944 * that we are waiting for inotify events now. */
3e0e196e 945 bus_set_state(b, BUS_WATCH_BIND);
8a5cd31e
LP
946 return 1;
947 }
948
949 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
950 r = bus_socket_inotify_setup(b);
951 if (r < 0)
952 return r;
953
954 /* Let's now try to connect a second time, because in theory there's otherwise a race
955 * here: the socket might have been created in the time between our first connect() and
956 * the time we set up the inotify logic. But let's remember that we set up inotify now,
957 * so that we don't do the connect() more than twice. */
958 inotify_done = true;
959
960 } else
961 return -errno;
962 } else
963 break;
a7e3212d
LP
964 }
965
8a5cd31e
LP
966 /* Yay, established, we don't need no inotify anymore! */
967 bus_close_inotify_fd(b);
968
a7e3212d
LP
969 return bus_socket_start_auth(b);
970}
971
972int bus_socket_exec(sd_bus *b) {
e82c9509 973 int s[2], r;
a7e3212d
LP
974
975 assert(b);
e82c9509
LP
976 assert(b->input_fd < 0);
977 assert(b->output_fd < 0);
a7e3212d 978 assert(b->exec_path);
392cf1d0 979 assert(b->busexec_pid == 0);
a7e3212d 980
87fa2e21
ZJS
981 if (DEBUG_LOGGING) {
982 _cleanup_free_ char *line = NULL;
983
984 if (b->exec_argv)
4ef15008 985 line = quote_command_line(b->exec_argv, SHELL_ESCAPE_EMPTY);
87fa2e21
ZJS
986
987 log_debug("sd-bus: starting bus%s%s with %s%s",
988 b->description ? " " : "", strempty(b->description),
989 line ?: b->exec_path,
990 b->exec_argv && !line ? "…" : "");
991 }
165fee86 992
e82c9509
LP
993 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
994 if (r < 0)
a7e3212d
LP
995 return -errno;
996
911f8f01
YW
997 r = safe_fork_full("(sd-busexec)",
998 NULL,
999 s+1, 1,
1000 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE, &b->busexec_pid);
4c253ed1 1001 if (r < 0) {
3d94f76c 1002 safe_close_pair(s);
4c253ed1 1003 return r;
a7e3212d 1004 }
4c253ed1 1005 if (r == 0) {
a7e3212d
LP
1006 /* Child */
1007
aedec452
LP
1008 r = rearrange_stdio(s[1], s[1], STDERR_FILENO);
1009 TAKE_FD(s[1]);
1010 if (r < 0)
2b33ab09 1011 _exit(EXIT_FAILURE);
a7e3212d 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 1310 events = fd_wait_for_event(b->output_fd, POLLOUT, 0);
3022916b
LP
1311 if (events < 0) {
1312 if (ERRNO_IS_TRANSIENT(events))
1313 return 0;
0f2d351f 1314 return events;
3022916b 1315 }
0f2d351f 1316 if (!(events & (POLLOUT|POLLERR|POLLHUP)))
a7e3212d
LP
1317 return 0;
1318
e82c9509 1319 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
a7e3212d
LP
1320 if (r < 0)
1321 b->last_connect_error = errno;
1322 else if (error != 0)
1323 b->last_connect_error = error;
0f2d351f 1324 else if (events & (POLLERR|POLLHUP))
a7e3212d
LP
1325 b->last_connect_error = ECONNREFUSED;
1326 else
1327 return bus_socket_start_auth(b);
1328
1329 return bus_next_address(b);
1330}
1331
1332int bus_socket_process_authenticating(sd_bus *b) {
1333 int r;
1334
1335 assert(b);
1336 assert(b->state == BUS_AUTHENTICATING);
1337
1338 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1339 return -ETIMEDOUT;
1340
1341 r = bus_socket_write_auth(b);
1342 if (r != 0)
1343 return r;
1344
1345 return bus_socket_read_auth(b);
1346}
8a5cd31e
LP
1347
1348int bus_socket_process_watch_bind(sd_bus *b) {
1349 int r, q;
1350
1351 assert(b);
1352 assert(b->state == BUS_WATCH_BIND);
1353 assert(b->inotify_fd >= 0);
1354
1355 r = flush_fd(b->inotify_fd);
1356 if (r <= 0)
1357 return r;
1358
1359 log_debug("Got inotify event on bus %s.", strna(b->description));
1360
1361 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1362 * to it again */
1363
1364 r = bus_socket_connect(b);
1365 if (r < 0)
1366 return r;
1367
1368 q = bus_attach_io_events(b);
1369 if (q < 0)
1370 return q;
1371
1372 q = bus_attach_inotify_event(b);
1373 if (q < 0)
1374 return q;
1375
1376 return r;
1377}