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