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