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