sd-bus: if we receive an invalid dbus message, ignore and proceeed
[thirdparty/systemd.git] / src / libsystemd / sd-bus / bus-socket.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
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
LP
14#include "bus-socket.h"
15#include "fd-util.h"
f97b34a6 16#include "format-util.h"
8a5cd31e 17#include "fs-util.h"
15a5e950 18#include "hexdecoct.h"
8a5cd31e 19#include "io-util.h"
a7e3212d
LP
20#include "macro.h"
21#include "missing.h"
8a5cd31e 22#include "path-util.h"
dccca82b 23#include "process-util.h"
595225af 24#include "rlimit-util.h"
7fc04b12 25#include "selinux-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
LP
30#include "utf8.h"
31#include "util.h"
a7e3212d 32
aec6d91f
LP
33#define SNDBUF_SIZE (8*1024*1024)
34
2181a7f5 35static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
a7e3212d
LP
36
37 while (size > 0) {
38 struct iovec *i = iov + *idx;
39
40 if (i->iov_len > size) {
41 i->iov_base = (uint8_t*) i->iov_base + size;
42 i->iov_len -= size;
43 return;
44 }
45
46 size -= i->iov_len;
47
5cfa2c3d 48 *i = IOVEC_MAKE(NULL, 0);
a7e3212d 49
313cefa1 50 (*idx)++;
a7e3212d
LP
51 }
52}
53
bc7fd8cd 54static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
2100fa10
LP
55 assert(m);
56 assert(p);
57 assert(sz > 0);
58
5cfa2c3d 59 m->iovec[m->n_iovec++] = IOVEC_MAKE((void*) p, sz);
bc7fd8cd
LP
60
61 return 0;
2100fa10
LP
62}
63
bc7fd8cd
LP
64static int bus_message_setup_iovec(sd_bus_message *m) {
65 struct bus_body_part *part;
13c299d3 66 unsigned n, i;
bc7fd8cd
LP
67 int r;
68
2100fa10
LP
69 assert(m);
70 assert(m->sealed);
71
72 if (m->n_iovec > 0)
bc7fd8cd
LP
73 return 0;
74
75 assert(!m->iovec);
2100fa10 76
c91cb83c 77 n = 1 + m->n_body_parts;
bc7fd8cd
LP
78 if (n < ELEMENTSOF(m->iovec_fixed))
79 m->iovec = m->iovec_fixed;
80 else {
81 m->iovec = new(struct iovec, n);
66b26c5c
LP
82 if (!m->iovec) {
83 r = -ENOMEM;
84 goto fail;
85 }
bc7fd8cd 86 }
2100fa10 87
c91cb83c 88 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
bc7fd8cd 89 if (r < 0)
66b26c5c 90 goto fail;
2100fa10 91
9b29bb68 92 MESSAGE_FOREACH_PART(part, i, m) {
66b26c5c
LP
93 r = bus_body_part_map(part);
94 if (r < 0)
95 goto fail;
96
bc7fd8cd
LP
97 r = append_iovec(m, part->data, part->size);
98 if (r < 0)
66b26c5c 99 goto fail;
bc7fd8cd
LP
100 }
101
102 assert(n == m->n_iovec);
103
104 return 0;
66b26c5c
LP
105
106fail:
107 m->poisoned = true;
108 return r;
2100fa10
LP
109}
110
2181a7f5
LP
111bool bus_socket_auth_needs_write(sd_bus *b) {
112
113 unsigned i;
114
115 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
116 return false;
117
118 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
119 struct iovec *j = b->auth_iovec + i;
120
121 if (j->iov_len > 0)
122 return true;
123 }
124
125 return false;
126}
127
a7e3212d 128static int bus_socket_write_auth(sd_bus *b) {
a7e3212d
LP
129 ssize_t k;
130
131 assert(b);
132 assert(b->state == BUS_AUTHENTICATING);
133
2181a7f5 134 if (!bus_socket_auth_needs_write(b))
a7e3212d
LP
135 return 0;
136
15d5af81
LP
137 if (b->prefer_writev)
138 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
139 else {
140 struct msghdr mh;
141 zero(mh);
142
143 mh.msg_iov = b->auth_iovec + b->auth_index;
144 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
145
146 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
147 if (k < 0 && errno == ENOTSOCK) {
148 b->prefer_writev = true;
149 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
150 }
151 }
a7e3212d 152
a7e3212d
LP
153 if (k < 0)
154 return errno == EAGAIN ? 0 : -errno;
155
156 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
a7e3212d
LP
157 return 1;
158}
159
2181a7f5 160static int bus_socket_auth_verify_client(sd_bus *b) {
a7e3212d
LP
161 char *e, *f, *start;
162 sd_id128_t peer;
163 unsigned i;
164 int r;
165
2181a7f5
LP
166 assert(b);
167
a7e3212d
LP
168 /* We expect two response lines: "OK" and possibly
169 * "AGREE_UNIX_FD" */
170
6e6c21c8 171 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
a7e3212d
LP
172 if (!e)
173 return 0;
174
c7db1984 175 if (b->accept_fd) {
a7e3212d
LP
176 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
177 if (!f)
178 return 0;
179
180 start = f + 2;
181 } else {
182 f = NULL;
183 start = e + 2;
184 }
185
186 /* Nice! We got all the lines we need. First check the OK
187 * line */
188
189 if (e - (char*) b->rbuffer != 3 + 32)
190 return -EPERM;
191
192 if (memcmp(b->rbuffer, "OK ", 3))
193 return -EPERM;
194
2181a7f5
LP
195 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
196
a7e3212d
LP
197 for (i = 0; i < 32; i += 2) {
198 int x, y;
199
200 x = unhexchar(((char*) b->rbuffer)[3 + i]);
201 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
202
203 if (x < 0 || y < 0)
204 return -EINVAL;
205
206 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
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
LP
214
215 /* And possibly check the second line, too */
216
217 if (f)
218 b->can_fds =
fbd0b64f
LP
219 (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
220 memcmp(e + 2, "AGREE_UNIX_FD",
221 STRLEN("AGREE_UNIX_FD")) == 0;
a7e3212d
LP
222
223 b->rbuffer_size -= (start - (char*) b->rbuffer);
224 memmove(b->rbuffer, start, b->rbuffer_size);
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
283 /* We don't do any real authentication here. Instead, we if
284 * the owner of this bus wanted authentication he should have
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;
381 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
382 if (!e)
383 return processed;
384
385 l = e - line;
386
387 if (line_begins(line, l, "AUTH ANONYMOUS")) {
388
389 r = verify_anonymous_token(b, line + 14, l - 14);
390 if (r < 0)
391 return r;
392 if (r == 0)
393 r = bus_socket_auth_write(b, "REJECTED\r\n");
394 else {
395 b->auth = BUS_AUTH_ANONYMOUS;
396 r = bus_socket_auth_write_ok(b);
397 }
398
399 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
400
401 r = verify_external_token(b, line + 13, l - 13);
402 if (r < 0)
403 return r;
404 if (r == 0)
405 r = bus_socket_auth_write(b, "REJECTED\r\n");
406 else {
407 b->auth = BUS_AUTH_EXTERNAL;
408 r = bus_socket_auth_write_ok(b);
409 }
410
411 } else if (line_begins(line, l, "AUTH"))
412 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
413 else if (line_equals(line, l, "CANCEL") ||
414 line_begins(line, l, "ERROR")) {
415
416 b->auth = _BUS_AUTH_INVALID;
417 r = bus_socket_auth_write(b, "REJECTED\r\n");
418
419 } else if (line_equals(line, l, "BEGIN")) {
420
421 if (b->auth == _BUS_AUTH_INVALID)
422 r = bus_socket_auth_write(b, "ERROR\r\n");
423 else {
424 /* We can't leave from the auth phase
425 * before we haven't written
426 * everything queued, so let's check
427 * that */
428
429 if (bus_socket_auth_needs_write(b))
430 return 1;
431
432 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
433 memmove(b->rbuffer, e + 2, b->rbuffer_size);
434 return bus_start_running(b);
435 }
436
437 } else if (line_begins(line, l, "DATA")) {
438
439 if (b->auth == _BUS_AUTH_INVALID)
440 r = bus_socket_auth_write(b, "ERROR\r\n");
441 else {
442 if (b->auth == BUS_AUTH_ANONYMOUS)
443 r = verify_anonymous_token(b, line + 4, l - 4);
444 else
445 r = verify_external_token(b, line + 4, l - 4);
446
447 if (r < 0)
448 return r;
449 if (r == 0) {
450 b->auth = _BUS_AUTH_INVALID;
451 r = bus_socket_auth_write(b, "REJECTED\r\n");
452 } else
453 r = bus_socket_auth_write_ok(b);
454 }
455 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
c7db1984 456 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
2181a7f5
LP
457 r = bus_socket_auth_write(b, "ERROR\r\n");
458 else {
459 b->can_fds = true;
460 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
461 }
462 } else
463 r = bus_socket_auth_write(b, "ERROR\r\n");
464
465 if (r < 0)
466 return r;
467
468 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
469
470 processed = true;
471 }
472}
473
474static int bus_socket_auth_verify(sd_bus *b) {
475 assert(b);
476
477 if (b->is_server)
478 return bus_socket_auth_verify_server(b);
479 else
480 return bus_socket_auth_verify_client(b);
481}
482
a7e3212d
LP
483static int bus_socket_read_auth(sd_bus *b) {
484 struct msghdr mh;
7f4e6a1c 485 struct iovec iov = {};
a7e3212d
LP
486 size_t n;
487 ssize_t k;
488 int r;
489 void *p;
2181a7f5
LP
490 union {
491 struct cmsghdr cmsghdr;
d868f2a3 492 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
2181a7f5 493 } control;
15d5af81 494 bool handle_cmsg = false;
a7e3212d
LP
495
496 assert(b);
2181a7f5 497 assert(b->state == BUS_AUTHENTICATING);
a7e3212d
LP
498
499 r = bus_socket_auth_verify(b);
500 if (r != 0)
501 return r;
502
9607d947 503 n = MAX(256u, b->rbuffer_size * 2);
a7e3212d
LP
504
505 if (n > BUS_AUTH_SIZE_MAX)
506 n = BUS_AUTH_SIZE_MAX;
507
508 if (b->rbuffer_size >= n)
509 return -ENOBUFS;
510
511 p = realloc(b->rbuffer, n);
512 if (!p)
513 return -ENOMEM;
514
515 b->rbuffer = p;
516
5cfa2c3d 517 iov = IOVEC_MAKE((uint8_t *)b->rbuffer + b->rbuffer_size, n - b->rbuffer_size);
a7e3212d 518
15d5af81
LP
519 if (b->prefer_readv)
520 k = readv(b->input_fd, &iov, 1);
521 else {
522 zero(mh);
523 mh.msg_iov = &iov;
524 mh.msg_iovlen = 1;
525 mh.msg_control = &control;
526 mh.msg_controllen = sizeof(control);
527
a6887cc0 528 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
15d5af81
LP
529 if (k < 0 && errno == ENOTSOCK) {
530 b->prefer_readv = true;
531 k = readv(b->input_fd, &iov, 1);
532 } else
533 handle_cmsg = true;
534 }
a7e3212d
LP
535 if (k < 0)
536 return errno == EAGAIN ? 0 : -errno;
537 if (k == 0)
538 return -ECONNRESET;
539
540 b->rbuffer_size += k;
541
2a1288ff
LP
542 if (handle_cmsg) {
543 struct cmsghdr *cmsg;
544
545 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
546 if (cmsg->cmsg_level == SOL_SOCKET &&
547 cmsg->cmsg_type == SCM_RIGHTS) {
548 int j;
549
550 /* Whut? We received fds during the auth
551 * protocol? Somebody is playing games with
552 * us. Close them all, and fail */
553 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
554 close_many((int*) CMSG_DATA(cmsg), j);
555 return -EIO;
d868f2a3
ZJS
556 } else
557 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
558 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 559 }
2181a7f5 560
a7e3212d
LP
561 r = bus_socket_auth_verify(b);
562 if (r != 0)
563 return r;
564
565 return 1;
566}
567
8f04d2eb 568void bus_socket_setup(sd_bus *b) {
a7e3212d
LP
569 assert(b);
570
aec6d91f 571 /* Increase the buffers to 8 MB */
6ae22ffb
LP
572 (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
573 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
a7e3212d 574
e1d337d4 575 b->message_version = 1;
0f437184 576 b->message_endian = 0;
8f04d2eb 577}
e1d337d4 578
8f04d2eb 579static void bus_get_peercred(sd_bus *b) {
c4e6556c
ZJS
580 int r;
581
8f04d2eb 582 assert(b);
18ac4643
LP
583 assert(!b->ucred_valid);
584 assert(!b->label);
585 assert(b->n_groups == (size_t) -1);
8f04d2eb
LP
586
587 /* Get the peer for socketpair() sockets */
eff05270 588 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
c4e6556c
ZJS
589
590 /* Get the SELinux context of the peer */
db7d1dca 591 r = getpeersec(b->input_fd, &b->label);
18ac4643 592 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
db7d1dca 593 log_debug_errno(r, "Failed to determine peer security context: %m");
18ac4643
LP
594
595 /* Get the list of auxiliary groups of the peer */
596 r = getpeergroups(b->input_fd, &b->groups);
c599b325 597 if (r >= 0)
18ac4643 598 b->n_groups = (size_t) r;
c599b325
ZJS
599 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
600 log_debug_errno(r, "Failed to determine peer's group list: %m");
a7e3212d
LP
601}
602
2181a7f5 603static int bus_socket_start_auth_client(sd_bus *b) {
a7e3212d 604 size_t l;
2181a7f5 605 const char *auth_suffix, *auth_prefix;
a7e3212d
LP
606
607 assert(b);
608
2181a7f5
LP
609 if (b->anonymous_auth) {
610 auth_prefix = "\0AUTH ANONYMOUS ";
a7e3212d 611
2181a7f5
LP
612 /* For ANONYMOUS auth we send some arbitrary "trace" string */
613 l = 9;
614 b->auth_buffer = hexmem("anonymous", l);
615 } else {
5ffa8c81 616 char text[DECIMAL_STR_MAX(uid_t) + 1];
a7e3212d 617
2181a7f5 618 auth_prefix = "\0AUTH EXTERNAL ";
a7e3212d 619
5ffa8c81 620 xsprintf(text, UID_FMT, geteuid());
a7e3212d 621
2181a7f5
LP
622 l = strlen(text);
623 b->auth_buffer = hexmem(text, l);
624 }
625
626 if (!b->auth_buffer)
a7e3212d
LP
627 return -ENOMEM;
628
c7db1984 629 if (b->accept_fd)
2181a7f5
LP
630 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
631 else
632 auth_suffix = "\r\nBEGIN\r\n";
a7e3212d 633
5cfa2c3d
LP
634 b->auth_iovec[0] = IOVEC_MAKE((void*) auth_prefix, 1 + strlen(auth_prefix + 1));
635 b->auth_iovec[1] = IOVEC_MAKE(b->auth_buffer, l * 2);
636 b->auth_iovec[2] = IOVEC_MAKE_STRING(auth_suffix);
a7e3212d
LP
637
638 return bus_socket_write_auth(b);
639}
640
a7893c6b 641int bus_socket_start_auth(sd_bus *b) {
2181a7f5
LP
642 assert(b);
643
8f04d2eb
LP
644 bus_get_peercred(b);
645
3e0e196e 646 bus_set_state(b, BUS_AUTHENTICATING);
036d61b3 647 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
2181a7f5 648
9ab32f9d 649 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 650 b->accept_fd = false;
2181a7f5 651
9ab32f9d
LP
652 if (b->output_fd != b->input_fd)
653 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
c7db1984 654 b->accept_fd = false;
e82c9509 655
2181a7f5
LP
656 if (b->is_server)
657 return bus_socket_read_auth(b);
658 else
659 return bus_socket_start_auth_client(b);
660}
661
8a5cd31e
LP
662static int bus_socket_inotify_setup(sd_bus *b) {
663 _cleanup_free_ int *new_watches = NULL;
664 _cleanup_free_ char *absolute = NULL;
665 size_t n_allocated = 0, n = 0, done = 0, i;
666 unsigned max_follow = 32;
667 const char *p;
668 int wd, r;
669
670 assert(b);
671 assert(b->watch_bind);
672 assert(b->sockaddr.sa.sa_family == AF_UNIX);
673 assert(b->sockaddr.un.sun_path[0] != 0);
674
675 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
676 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
677 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
678 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
679 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
680 * components. */
681
682 if (b->inotify_fd < 0) {
683 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
684 if (b->inotify_fd < 0)
685 return -errno;
7fe2903c
LP
686
687 b->inotify_fd = fd_move_above_stdio(b->inotify_fd);
8a5cd31e
LP
688 }
689
690 /* Make sure the path is NUL terminated */
691 p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
692
693 /* Make sure the path is absolute */
694 r = path_make_absolute_cwd(p, &absolute);
695 if (r < 0)
696 goto fail;
697
698 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
699 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
700 * they are removed or renamed. */
701
702 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
703 r = -ENOMEM;
704 goto fail;
705 }
706
707 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
708 * always exists */
709 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
710 if (wd < 0) {
711 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
712 goto fail;
713 } else
714 new_watches[n++] = wd;
715
716 for (;;) {
717 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
718 size_t n_slashes, n_component;
719 char *c = NULL;
720
721 n_slashes = strspn(absolute + done, "/");
722 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
723
724 if (n_component == 0) /* The end */
725 break;
726
727 component = strndup(absolute + done, n_component);
728 if (!component) {
729 r = -ENOMEM;
730 goto fail;
731 }
732
733 /* A trailing slash? That's a directory, and not a socket then */
734 if (path_equal(component, "/")) {
735 r = -EISDIR;
736 goto fail;
737 }
738
739 /* A single dot? Let's eat this up */
740 if (path_equal(component, "/.")) {
741 done += n_component;
742 continue;
743 }
744
745 prefix = strndup(absolute, done + n_component);
746 if (!prefix) {
747 r = -ENOMEM;
748 goto fail;
749 }
750
751 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
752 r = -ENOMEM;
753 goto fail;
754 }
755
756 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
757 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
758
759 if (wd < 0) {
760 if (IN_SET(errno, ENOENT, ELOOP))
761 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
762
945403e6 763 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", empty_to_root(prefix));
8a5cd31e
LP
764 goto fail;
765 } else
766 new_watches[n++] = wd;
767
768 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
769 r = readlink_malloc(prefix, &destination);
770 if (r == -EINVAL) { /* not a symlink */
771 done += n_component;
772 continue;
773 }
774 if (r < 0)
775 goto fail;
776
777 if (isempty(destination)) { /* Empty symlink target? Yuck! */
778 r = -EINVAL;
779 goto fail;
780 }
781
782 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
783 r = -ELOOP;
784 goto fail;
785 }
786
787 if (path_is_absolute(destination)) {
788 /* For absolute symlinks we build the new path and start anew */
789 c = strjoin(destination, absolute + done + n_component);
790 done = 0;
791 } else {
792 _cleanup_free_ char *t = NULL;
793
794 /* For relative symlinks we replace the last component, and try again */
795 t = strndup(absolute, done);
796 if (!t)
797 return -ENOMEM;
798
799 c = strjoin(t, "/", destination, absolute + done + n_component);
800 }
801 if (!c) {
802 r = -ENOMEM;
803 goto fail;
804 }
805
806 free(absolute);
807 absolute = c;
808
809 max_follow--;
810 }
811
812 /* And now, let's remove all watches from the previous iteration we don't need anymore */
813 for (i = 0; i < b->n_inotify_watches; i++) {
814 bool found = false;
815 size_t j;
816
817 for (j = 0; j < n; j++)
818 if (new_watches[j] == b->inotify_watches[i]) {
819 found = true;
820 break;
821 }
822
823 if (found)
824 continue;
825
826 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
827 }
828
829 free_and_replace(b->inotify_watches, new_watches);
830 b->n_inotify_watches = n;
831
832 return 0;
833
834fail:
835 bus_close_inotify_fd(b);
836 return r;
837}
838
a7e3212d 839int bus_socket_connect(sd_bus *b) {
8a5cd31e 840 bool inotify_done = false;
a7e3212d
LP
841 int r;
842
843 assert(b);
a7e3212d 844
8a5cd31e
LP
845 for (;;) {
846 assert(b->input_fd < 0);
847 assert(b->output_fd < 0);
848 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
a7e3212d 849
8a5cd31e
LP
850 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
851 if (b->input_fd < 0)
852 return -errno;
e82c9509 853
7fe2903c
LP
854 b->input_fd = fd_move_above_stdio(b->input_fd);
855
8a5cd31e
LP
856 b->output_fd = b->input_fd;
857 bus_socket_setup(b);
a7e3212d 858
8a5cd31e
LP
859 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
860 if (errno == EINPROGRESS) {
a7e3212d 861
8a5cd31e
LP
862 /* If we have any inotify watches open, close them now, we don't need them anymore, as
863 * we have successfully initiated a connection */
864 bus_close_inotify_fd(b);
865
866 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
867 * we start parsing the address string. The only reason we set the state explicitly
868 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
3e0e196e 869 bus_set_state(b, BUS_OPENING);
8a5cd31e
LP
870 return 1;
871 }
872
873 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
874 b->watch_bind &&
875 b->sockaddr.sa.sa_family == AF_UNIX &&
876 b->sockaddr.un.sun_path[0] != 0) {
877
878 /* This connection attempt failed, let's release the socket for now, and start with a
879 * fresh one when reconnecting. */
880 bus_close_io_fds(b);
881
882 if (inotify_done) {
883 /* inotify set up already, don't do it again, just return now, and remember
884 * that we are waiting for inotify events now. */
3e0e196e 885 bus_set_state(b, BUS_WATCH_BIND);
8a5cd31e
LP
886 return 1;
887 }
888
889 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
890 r = bus_socket_inotify_setup(b);
891 if (r < 0)
892 return r;
893
894 /* Let's now try to connect a second time, because in theory there's otherwise a race
895 * here: the socket might have been created in the time between our first connect() and
896 * the time we set up the inotify logic. But let's remember that we set up inotify now,
897 * so that we don't do the connect() more than twice. */
898 inotify_done = true;
899
900 } else
901 return -errno;
902 } else
903 break;
a7e3212d
LP
904 }
905
8a5cd31e
LP
906 /* Yay, established, we don't need no inotify anymore! */
907 bus_close_inotify_fd(b);
908
a7e3212d
LP
909 return bus_socket_start_auth(b);
910}
911
912int bus_socket_exec(sd_bus *b) {
e82c9509 913 int s[2], r;
a7e3212d
LP
914
915 assert(b);
e82c9509
LP
916 assert(b->input_fd < 0);
917 assert(b->output_fd < 0);
a7e3212d 918 assert(b->exec_path);
392cf1d0 919 assert(b->busexec_pid == 0);
a7e3212d 920
e82c9509
LP
921 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
922 if (r < 0)
a7e3212d
LP
923 return -errno;
924
392cf1d0 925 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &b->busexec_pid);
4c253ed1 926 if (r < 0) {
3d94f76c 927 safe_close_pair(s);
4c253ed1 928 return r;
a7e3212d 929 }
4c253ed1 930 if (r == 0) {
a7e3212d
LP
931 /* Child */
932
2b33ab09
LP
933 if (rearrange_stdio(s[1], s[1], STDERR_FILENO) < 0)
934 _exit(EXIT_FAILURE);
a7e3212d 935
595225af
LP
936 (void) rlimit_nofile_safe();
937
a7e3212d
LP
938 if (b->exec_argv)
939 execvp(b->exec_path, b->exec_argv);
940 else {
941 const char *argv[] = { b->exec_path, NULL };
942 execvp(b->exec_path, (char**) argv);
943 }
944
945 _exit(EXIT_FAILURE);
946 }
947
03e334a1 948 safe_close(s[1]);
7fe2903c 949 b->output_fd = b->input_fd = fd_move_above_stdio(s[0]);
a7e3212d 950
8f04d2eb 951 bus_socket_setup(b);
e1d337d4 952
a7e3212d
LP
953 return bus_socket_start_auth(b);
954}
955
956int bus_socket_take_fd(sd_bus *b) {
a7e3212d
LP
957 assert(b);
958
8f04d2eb 959 bus_socket_setup(b);
a7e3212d
LP
960
961 return bus_socket_start_auth(b);
962}
963
964int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
a7e3212d
LP
965 struct iovec *iov;
966 ssize_t k;
967 size_t n;
968 unsigned j;
bc7fd8cd 969 int r;
a7e3212d
LP
970
971 assert(bus);
972 assert(m);
973 assert(idx);
945c2931 974 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 975
6629161f 976 if (*idx >= BUS_MESSAGE_SIZE(m))
a7e3212d 977 return 0;
a7e3212d 978
bc7fd8cd
LP
979 r = bus_message_setup_iovec(m);
980 if (r < 0)
981 return r;
2100fa10 982
a7e3212d 983 n = m->n_iovec * sizeof(struct iovec);
6e9417f5 984 iov = newa(struct iovec, n);
75f32f04 985 memcpy_safe(iov, m->iovec, n);
a7e3212d
LP
986
987 j = 0;
988 iovec_advance(iov, &j, *idx);
989
15d5af81
LP
990 if (bus->prefer_writev)
991 k = writev(bus->output_fd, iov, m->n_iovec);
992 else {
7f4e6a1c
ZJS
993 struct msghdr mh = {
994 .msg_iov = iov,
995 .msg_iovlen = m->n_iovec,
996 };
15d5af81 997
f29eef2e 998 if (m->n_fds > 0 && *idx == 0) {
15d5af81 999 struct cmsghdr *control;
15d5af81 1000
7f4e6a1c
ZJS
1001 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1002 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
15d5af81
LP
1003 control->cmsg_level = SOL_SOCKET;
1004 control->cmsg_type = SCM_RIGHTS;
15d5af81
LP
1005 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1006 }
1007
15d5af81
LP
1008 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1009 if (k < 0 && errno == ENOTSOCK) {
1010 bus->prefer_writev = true;
1011 k = writev(bus->output_fd, iov, m->n_iovec);
1012 }
1013 }
a7e3212d 1014
a7e3212d
LP
1015 if (k < 0)
1016 return errno == EAGAIN ? 0 : -errno;
1017
1018 *idx += (size_t) k;
1019 return 1;
1020}
1021
1022static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1023 uint32_t a, b;
1024 uint8_t e;
1025 uint64_t sum;
1026
1027 assert(bus);
1028 assert(need);
945c2931 1029 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1030
1031 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1032 *need = sizeof(struct bus_header) + 8;
1033
1034 /* Minimum message size:
1035 *
1036 * Header +
1037 *
1038 * Method Call: +2 string headers
1039 * Signal: +3 string headers
1040 * Method Error: +1 string headers
1041 * +1 uint32 headers
1042 * Method Reply: +1 uint32 headers
1043 *
1044 * A string header is at least 9 bytes
1045 * A uint32 header is at least 8 bytes
1046 *
1047 * Hence the minimum message size of a valid message
1048 * is header + 8 bytes */
1049
1050 return 0;
1051 }
1052
1053 a = ((const uint32_t*) bus->rbuffer)[1];
1054 b = ((const uint32_t*) bus->rbuffer)[3];
1055
1056 e = ((const uint8_t*) bus->rbuffer)[0];
0461f8cd 1057 if (e == BUS_LITTLE_ENDIAN) {
a7e3212d
LP
1058 a = le32toh(a);
1059 b = le32toh(b);
0461f8cd 1060 } else if (e == BUS_BIG_ENDIAN) {
a7e3212d
LP
1061 a = be32toh(a);
1062 b = be32toh(b);
1063 } else
1064 return -EBADMSG;
1065
1066 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1067 if (sum >= BUS_MESSAGE_SIZE_MAX)
1068 return -ENOBUFS;
1069
1070 *need = (size_t) sum;
1071 return 0;
1072}
1073
7d22c717 1074static int bus_socket_make_message(sd_bus *bus, size_t size) {
6d586a13 1075 sd_bus_message *t = NULL;
a7e3212d
LP
1076 void *b;
1077 int r;
1078
1079 assert(bus);
a7e3212d 1080 assert(bus->rbuffer_size >= size);
945c2931 1081 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d 1082
7adc46fc
LP
1083 r = bus_rqueue_make_room(bus);
1084 if (r < 0)
1085 return r;
1086
a7e3212d
LP
1087 if (bus->rbuffer_size > size) {
1088 b = memdup((const uint8_t*) bus->rbuffer + size,
1089 bus->rbuffer_size - size);
1090 if (!b)
1091 return -ENOMEM;
1092 } else
1093 b = NULL;
1094
df2d202e
LP
1095 r = bus_message_from_malloc(bus,
1096 bus->rbuffer, size,
a7e3212d 1097 bus->fds, bus->n_fds,
038f9863 1098 NULL,
a7e3212d 1099 &t);
6d586a13
LP
1100 if (r == -EBADMSG)
1101 log_debug_errno(r, "Received invalid message from connection %s, dropping.", strna(bus->description));
1102 else if (r < 0) {
a7e3212d
LP
1103 free(b);
1104 return r;
1105 }
1106
1107 bus->rbuffer = b;
1108 bus->rbuffer_size -= size;
1109
1110 bus->fds = NULL;
1111 bus->n_fds = 0;
1112
6d586a13
LP
1113 if (t)
1114 bus->rqueue[bus->rqueue_size++] = t;
7d22c717 1115
a7e3212d
LP
1116 return 1;
1117}
1118
7d22c717 1119int bus_socket_read_message(sd_bus *bus) {
a7e3212d 1120 struct msghdr mh;
7f4e6a1c 1121 struct iovec iov = {};
a7e3212d
LP
1122 ssize_t k;
1123 size_t need;
1124 int r;
1125 void *b;
1126 union {
1127 struct cmsghdr cmsghdr;
d868f2a3 1128 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
a7e3212d 1129 } control;
4d3a5b10 1130 bool handle_cmsg = false;
a7e3212d
LP
1131
1132 assert(bus);
945c2931 1133 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
a7e3212d
LP
1134
1135 r = bus_socket_read_message_need(bus, &need);
1136 if (r < 0)
1137 return r;
1138
1139 if (bus->rbuffer_size >= need)
7d22c717 1140 return bus_socket_make_message(bus, need);
a7e3212d
LP
1141
1142 b = realloc(bus->rbuffer, need);
1143 if (!b)
1144 return -ENOMEM;
1145
1146 bus->rbuffer = b;
1147
5cfa2c3d 1148 iov = IOVEC_MAKE((uint8_t *)bus->rbuffer + bus->rbuffer_size, need - bus->rbuffer_size);
a7e3212d 1149
15d5af81
LP
1150 if (bus->prefer_readv)
1151 k = readv(bus->input_fd, &iov, 1);
1152 else {
1153 zero(mh);
1154 mh.msg_iov = &iov;
1155 mh.msg_iovlen = 1;
1156 mh.msg_control = &control;
1157 mh.msg_controllen = sizeof(control);
1158
a6887cc0 1159 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
15d5af81
LP
1160 if (k < 0 && errno == ENOTSOCK) {
1161 bus->prefer_readv = true;
1162 k = readv(bus->input_fd, &iov, 1);
1163 } else
1164 handle_cmsg = true;
1165 }
a7e3212d
LP
1166 if (k < 0)
1167 return errno == EAGAIN ? 0 : -errno;
1168 if (k == 0)
1169 return -ECONNRESET;
1170
1171 bus->rbuffer_size += k;
1172
2a1288ff
LP
1173 if (handle_cmsg) {
1174 struct cmsghdr *cmsg;
1175
1176 CMSG_FOREACH(cmsg, &mh)
15d5af81
LP
1177 if (cmsg->cmsg_level == SOL_SOCKET &&
1178 cmsg->cmsg_type == SCM_RIGHTS) {
7fe2903c 1179 int n, *f, i;
15d5af81
LP
1180
1181 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1182
1183 if (!bus->can_fds) {
1184 /* Whut? We received fds but this
1185 * isn't actually enabled? Close them,
1186 * and fail */
1187
1188 close_many((int*) CMSG_DATA(cmsg), n);
1189 return -EIO;
1190 }
1191
62d74c78 1192 f = reallocarray(bus->fds, bus->n_fds + n, sizeof(int));
15d5af81
LP
1193 if (!f) {
1194 close_many((int*) CMSG_DATA(cmsg), n);
1195 return -ENOMEM;
1196 }
1197
7fe2903c
LP
1198 for (i = 0; i < n; i++)
1199 f[bus->n_fds++] = fd_move_above_stdio(((int*) CMSG_DATA(cmsg))[i]);
15d5af81 1200 bus->fds = f;
d868f2a3
ZJS
1201 } else
1202 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1203 cmsg->cmsg_level, cmsg->cmsg_type);
2a1288ff 1204 }
a7e3212d
LP
1205
1206 r = bus_socket_read_message_need(bus, &need);
1207 if (r < 0)
1208 return r;
1209
1210 if (bus->rbuffer_size >= need)
7d22c717 1211 return bus_socket_make_message(bus, need);
a7e3212d
LP
1212
1213 return 1;
1214}
1215
1216int bus_socket_process_opening(sd_bus *b) {
1217 int error = 0;
1218 socklen_t slen = sizeof(error);
b92bea5d
ZJS
1219 struct pollfd p = {
1220 .fd = b->output_fd,
1221 .events = POLLOUT,
1222 };
a7e3212d
LP
1223 int r;
1224
a7e3212d
LP
1225 assert(b->state == BUS_OPENING);
1226
a7e3212d
LP
1227 r = poll(&p, 1, 0);
1228 if (r < 0)
1229 return -errno;
1230
1231 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1232 return 0;
1233
e82c9509 1234 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
a7e3212d
LP
1235 if (r < 0)
1236 b->last_connect_error = errno;
1237 else if (error != 0)
1238 b->last_connect_error = error;
1239 else if (p.revents & (POLLERR|POLLHUP))
1240 b->last_connect_error = ECONNREFUSED;
1241 else
1242 return bus_socket_start_auth(b);
1243
1244 return bus_next_address(b);
1245}
1246
1247int bus_socket_process_authenticating(sd_bus *b) {
1248 int r;
1249
1250 assert(b);
1251 assert(b->state == BUS_AUTHENTICATING);
1252
1253 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1254 return -ETIMEDOUT;
1255
1256 r = bus_socket_write_auth(b);
1257 if (r != 0)
1258 return r;
1259
1260 return bus_socket_read_auth(b);
1261}
8a5cd31e
LP
1262
1263int bus_socket_process_watch_bind(sd_bus *b) {
1264 int r, q;
1265
1266 assert(b);
1267 assert(b->state == BUS_WATCH_BIND);
1268 assert(b->inotify_fd >= 0);
1269
1270 r = flush_fd(b->inotify_fd);
1271 if (r <= 0)
1272 return r;
1273
1274 log_debug("Got inotify event on bus %s.", strna(b->description));
1275
1276 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1277 * to it again */
1278
1279 r = bus_socket_connect(b);
1280 if (r < 0)
1281 return r;
1282
1283 q = bus_attach_io_events(b);
1284 if (q < 0)
1285 return q;
1286
1287 q = bus_attach_inotify_event(b);
1288 if (q < 0)
1289 return q;
1290
1291 return r;
1292}