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