]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-bus/bus-socket.c
Merge pull request #7851 from msekletar/dbus-error-logging
[thirdparty/systemd.git] / src / libsystemd / sd-bus / bus-socket.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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>
22 #include <poll.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25
26 #include "sd-bus.h"
27 #include "sd-daemon.h"
28
29 #include "alloc-util.h"
30 #include "bus-internal.h"
31 #include "bus-message.h"
32 #include "bus-socket.h"
33 #include "fd-util.h"
34 #include "format-util.h"
35 #include "fs-util.h"
36 #include "hexdecoct.h"
37 #include "io-util.h"
38 #include "macro.h"
39 #include "missing.h"
40 #include "path-util.h"
41 #include "selinux-util.h"
42 #include "signal-util.h"
43 #include "stdio-util.h"
44 #include "string-util.h"
45 #include "user-util.h"
46 #include "utf8.h"
47 #include "util.h"
48
49 #define SNDBUF_SIZE (8*1024*1024)
50
51 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
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
67 (*idx)++;
68 }
69 }
70
71 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
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++;
79
80 return 0;
81 }
82
83 static int bus_message_setup_iovec(sd_bus_message *m) {
84 struct bus_body_part *part;
85 unsigned n, i;
86 int r;
87
88 assert(m);
89 assert(m->sealed);
90
91 if (m->n_iovec > 0)
92 return 0;
93
94 assert(!m->iovec);
95
96 n = 1 + m->n_body_parts;
97 if (n < ELEMENTSOF(m->iovec_fixed))
98 m->iovec = m->iovec_fixed;
99 else {
100 m->iovec = new(struct iovec, n);
101 if (!m->iovec) {
102 r = -ENOMEM;
103 goto fail;
104 }
105 }
106
107 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
108 if (r < 0)
109 goto fail;
110
111 MESSAGE_FOREACH_PART(part, i, m) {
112 r = bus_body_part_map(part);
113 if (r < 0)
114 goto fail;
115
116 r = append_iovec(m, part->data, part->size);
117 if (r < 0)
118 goto fail;
119 }
120
121 assert(n == m->n_iovec);
122
123 return 0;
124
125 fail:
126 m->poisoned = true;
127 return r;
128 }
129
130 bool 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
147 static int bus_socket_write_auth(sd_bus *b) {
148 ssize_t k;
149
150 assert(b);
151 assert(b->state == BUS_AUTHENTICATING);
152
153 if (!bus_socket_auth_needs_write(b))
154 return 0;
155
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 }
171
172 if (k < 0)
173 return errno == EAGAIN ? 0 : -errno;
174
175 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
176 return 1;
177 }
178
179 static int bus_socket_auth_verify_client(sd_bus *b) {
180 char *e, *f, *start;
181 sd_id128_t peer;
182 unsigned i;
183 int r;
184
185 assert(b);
186
187 /* We expect two response lines: "OK" and possibly
188 * "AGREE_UNIX_FD" */
189
190 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
191 if (!e)
192 return 0;
193
194 if (b->accept_fd) {
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
214 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
215
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
228 if (!sd_id128_is_null(b->server_id) &&
229 !sd_id128_equal(b->server_id, peer))
230 return -EPERM;
231
232 b->server_id = peer;
233
234 /* And possibly check the second line, too */
235
236 if (f)
237 b->can_fds =
238 (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
239 memcmp(e + 2, "AGREE_UNIX_FD",
240 STRLEN("AGREE_UNIX_FD")) == 0;
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
252 static 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
262 static 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
275 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
276 _cleanup_free_ char *token = NULL;
277 size_t len;
278 int r;
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;
291
292 r = unhexmem(p, l, (void **) &token, &len);
293 if (r < 0)
294 return 0;
295
296 if (memchr(token, 0, len))
297 return 0;
298
299 return !!utf8_is_valid(token);
300 }
301
302 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
303 _cleanup_free_ char *token = NULL;
304 size_t len;
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
312 if (!b->anonymous_auth && !b->ucred_valid)
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
324 r = unhexmem(p, l, (void**) &token, &len);
325 if (r < 0)
326 return 0;
327
328 if (memchr(token, 0, len))
329 return 0;
330
331 r = parse_uid(token, &u);
332 if (r < 0)
333 return 0;
334
335 /* We ignore the passed value if anonymous authentication is
336 * on anyway. */
337 if (!b->anonymous_auth && u != b->ucred.uid)
338 return 0;
339
340 return 1;
341 }
342
343 static 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 */
351 assert(IN_SET(b->auth_index, 0, 1));
352
353 l = strlen(t);
354 p = malloc(b->auth_iovec[0].iov_len + l);
355 if (!p)
356 return -ENOMEM;
357
358 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
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
370 static int bus_socket_auth_write_ok(sd_bus *b) {
371 char t[3 + 32 + 2 + 1];
372
373 assert(b);
374
375 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
376
377 return bus_socket_auth_write(b, t);
378 }
379
380 static 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
389 if (b->rbuffer_size < 1)
390 return 0;
391
392 /* First char must be a NUL byte */
393 if (*(char*) b->rbuffer != 0)
394 return -EIO;
395
396 if (b->rbuffer_size < 3)
397 return 0;
398
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")) {
481 if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
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
499 static 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
508 static int bus_socket_read_auth(sd_bus *b) {
509 struct msghdr mh;
510 struct iovec iov = {};
511 size_t n;
512 ssize_t k;
513 int r;
514 void *p;
515 union {
516 struct cmsghdr cmsghdr;
517 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
518 } control;
519 bool handle_cmsg = false;
520
521 assert(b);
522 assert(b->state == BUS_AUTHENTICATING);
523
524 r = bus_socket_auth_verify(b);
525 if (r != 0)
526 return r;
527
528 n = MAX(256u, b->rbuffer_size * 2);
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
542 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
543 iov.iov_len = n - b->rbuffer_size;
544
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 }
561 if (k < 0)
562 return errno == EAGAIN ? 0 : -errno;
563 if (k == 0)
564 return -ECONNRESET;
565
566 b->rbuffer_size += k;
567
568 if (handle_cmsg) {
569 struct cmsghdr *cmsg;
570
571 CMSG_FOREACH(cmsg, &mh)
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;
582 } else
583 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
584 cmsg->cmsg_level, cmsg->cmsg_type);
585 }
586
587 r = bus_socket_auth_verify(b);
588 if (r != 0)
589 return r;
590
591 return 1;
592 }
593
594 void bus_socket_setup(sd_bus *b) {
595 assert(b);
596
597 /* Increase the buffers to 8 MB */
598 (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
599 (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
600
601 b->message_version = 1;
602 b->message_endian = 0;
603 }
604
605 static void bus_get_peercred(sd_bus *b) {
606 int r;
607
608 assert(b);
609 assert(!b->ucred_valid);
610 assert(!b->label);
611 assert(b->n_groups == (size_t) -1);
612
613 /* Get the peer for socketpair() sockets */
614 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
615
616 /* Get the SELinux context of the peer */
617 r = getpeersec(b->input_fd, &b->label);
618 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
619 log_debug_errno(r, "Failed to determine peer security context: %m");
620
621 /* Get the list of auxiliary groups of the peer */
622 r = getpeergroups(b->input_fd, &b->groups);
623 if (r >= 0)
624 b->n_groups = (size_t) r;
625 else if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
626 log_debug_errno(r, "Failed to determine peer's group list: %m");
627 }
628
629 static int bus_socket_start_auth_client(sd_bus *b) {
630 size_t l;
631 const char *auth_suffix, *auth_prefix;
632
633 assert(b);
634
635 if (b->anonymous_auth) {
636 auth_prefix = "\0AUTH ANONYMOUS ";
637
638 /* For ANONYMOUS auth we send some arbitrary "trace" string */
639 l = 9;
640 b->auth_buffer = hexmem("anonymous", l);
641 } else {
642 char text[DECIMAL_STR_MAX(uid_t) + 1];
643
644 auth_prefix = "\0AUTH EXTERNAL ";
645
646 xsprintf(text, UID_FMT, geteuid());
647
648 l = strlen(text);
649 b->auth_buffer = hexmem(text, l);
650 }
651
652 if (!b->auth_buffer)
653 return -ENOMEM;
654
655 if (b->accept_fd)
656 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
657 else
658 auth_suffix = "\r\nBEGIN\r\n";
659
660 b->auth_iovec[0].iov_base = (void*) auth_prefix;
661 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
662 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
663 b->auth_iovec[1].iov_len = l * 2;
664 b->auth_iovec[2].iov_base = (void*) auth_suffix;
665 b->auth_iovec[2].iov_len = strlen(auth_suffix);
666
667 return bus_socket_write_auth(b);
668 }
669
670 int bus_socket_start_auth(sd_bus *b) {
671 assert(b);
672
673 bus_get_peercred(b);
674
675 bus_set_state(b, BUS_AUTHENTICATING);
676 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
677
678 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
679 b->accept_fd = false;
680
681 if (b->output_fd != b->input_fd)
682 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
683 b->accept_fd = false;
684
685 if (b->is_server)
686 return bus_socket_read_auth(b);
687 else
688 return bus_socket_start_auth_client(b);
689 }
690
691 static int bus_socket_inotify_setup(sd_bus *b) {
692 _cleanup_free_ int *new_watches = NULL;
693 _cleanup_free_ char *absolute = NULL;
694 size_t n_allocated = 0, n = 0, done = 0, i;
695 unsigned max_follow = 32;
696 const char *p;
697 int wd, r;
698
699 assert(b);
700 assert(b->watch_bind);
701 assert(b->sockaddr.sa.sa_family == AF_UNIX);
702 assert(b->sockaddr.un.sun_path[0] != 0);
703
704 /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
705 * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
706 * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
707 * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
708 * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
709 * components. */
710
711 if (b->inotify_fd < 0) {
712 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
713 if (b->inotify_fd < 0)
714 return -errno;
715 }
716
717 /* Make sure the path is NUL terminated */
718 p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
719
720 /* Make sure the path is absolute */
721 r = path_make_absolute_cwd(p, &absolute);
722 if (r < 0)
723 goto fail;
724
725 /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
726 * that exists we want to know when files are created or moved into it. For all parents of it we just care if
727 * they are removed or renamed. */
728
729 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
730 r = -ENOMEM;
731 goto fail;
732 }
733
734 /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
735 * always exists */
736 wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
737 if (wd < 0) {
738 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
739 goto fail;
740 } else
741 new_watches[n++] = wd;
742
743 for (;;) {
744 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
745 size_t n_slashes, n_component;
746 char *c = NULL;
747
748 n_slashes = strspn(absolute + done, "/");
749 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
750
751 if (n_component == 0) /* The end */
752 break;
753
754 component = strndup(absolute + done, n_component);
755 if (!component) {
756 r = -ENOMEM;
757 goto fail;
758 }
759
760 /* A trailing slash? That's a directory, and not a socket then */
761 if (path_equal(component, "/")) {
762 r = -EISDIR;
763 goto fail;
764 }
765
766 /* A single dot? Let's eat this up */
767 if (path_equal(component, "/.")) {
768 done += n_component;
769 continue;
770 }
771
772 prefix = strndup(absolute, done + n_component);
773 if (!prefix) {
774 r = -ENOMEM;
775 goto fail;
776 }
777
778 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
779 r = -ENOMEM;
780 goto fail;
781 }
782
783 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
784 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
785
786 if (wd < 0) {
787 if (IN_SET(errno, ENOENT, ELOOP))
788 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
789
790 r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", isempty(prefix) ? "/" : prefix);
791 goto fail;
792 } else
793 new_watches[n++] = wd;
794
795 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
796 r = readlink_malloc(prefix, &destination);
797 if (r == -EINVAL) { /* not a symlink */
798 done += n_component;
799 continue;
800 }
801 if (r < 0)
802 goto fail;
803
804 if (isempty(destination)) { /* Empty symlink target? Yuck! */
805 r = -EINVAL;
806 goto fail;
807 }
808
809 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
810 r = -ELOOP;
811 goto fail;
812 }
813
814 if (path_is_absolute(destination)) {
815 /* For absolute symlinks we build the new path and start anew */
816 c = strjoin(destination, absolute + done + n_component);
817 done = 0;
818 } else {
819 _cleanup_free_ char *t = NULL;
820
821 /* For relative symlinks we replace the last component, and try again */
822 t = strndup(absolute, done);
823 if (!t)
824 return -ENOMEM;
825
826 c = strjoin(t, "/", destination, absolute + done + n_component);
827 }
828 if (!c) {
829 r = -ENOMEM;
830 goto fail;
831 }
832
833 free(absolute);
834 absolute = c;
835
836 max_follow--;
837 }
838
839 /* And now, let's remove all watches from the previous iteration we don't need anymore */
840 for (i = 0; i < b->n_inotify_watches; i++) {
841 bool found = false;
842 size_t j;
843
844 for (j = 0; j < n; j++)
845 if (new_watches[j] == b->inotify_watches[i]) {
846 found = true;
847 break;
848 }
849
850 if (found)
851 continue;
852
853 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
854 }
855
856 free_and_replace(b->inotify_watches, new_watches);
857 b->n_inotify_watches = n;
858
859 return 0;
860
861 fail:
862 bus_close_inotify_fd(b);
863 return r;
864 }
865
866 int bus_socket_connect(sd_bus *b) {
867 bool inotify_done = false;
868 int r;
869
870 assert(b);
871
872 for (;;) {
873 assert(b->input_fd < 0);
874 assert(b->output_fd < 0);
875 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
876
877 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
878 if (b->input_fd < 0)
879 return -errno;
880
881 b->output_fd = b->input_fd;
882 bus_socket_setup(b);
883
884 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
885 if (errno == EINPROGRESS) {
886
887 /* If we have any inotify watches open, close them now, we don't need them anymore, as
888 * we have successfully initiated a connection */
889 bus_close_inotify_fd(b);
890
891 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
892 * we start parsing the address string. The only reason we set the state explicitly
893 * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
894 bus_set_state(b, BUS_OPENING);
895 return 1;
896 }
897
898 if (IN_SET(errno, ENOENT, ECONNREFUSED) && /* ENOENT → unix socket doesn't exist at all; ECONNREFUSED → unix socket stale */
899 b->watch_bind &&
900 b->sockaddr.sa.sa_family == AF_UNIX &&
901 b->sockaddr.un.sun_path[0] != 0) {
902
903 /* This connection attempt failed, let's release the socket for now, and start with a
904 * fresh one when reconnecting. */
905 bus_close_io_fds(b);
906
907 if (inotify_done) {
908 /* inotify set up already, don't do it again, just return now, and remember
909 * that we are waiting for inotify events now. */
910 bus_set_state(b, BUS_WATCH_BIND);
911 return 1;
912 }
913
914 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
915 r = bus_socket_inotify_setup(b);
916 if (r < 0)
917 return r;
918
919 /* Let's now try to connect a second time, because in theory there's otherwise a race
920 * here: the socket might have been created in the time between our first connect() and
921 * the time we set up the inotify logic. But let's remember that we set up inotify now,
922 * so that we don't do the connect() more than twice. */
923 inotify_done = true;
924
925 } else
926 return -errno;
927 } else
928 break;
929 }
930
931 /* Yay, established, we don't need no inotify anymore! */
932 bus_close_inotify_fd(b);
933
934 return bus_socket_start_auth(b);
935 }
936
937 int bus_socket_exec(sd_bus *b) {
938 int s[2], r;
939 pid_t pid;
940
941 assert(b);
942 assert(b->input_fd < 0);
943 assert(b->output_fd < 0);
944 assert(b->exec_path);
945
946 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
947 if (r < 0)
948 return -errno;
949
950 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &pid);
951 if (r < 0) {
952 safe_close_pair(s);
953 return r;
954 }
955 if (r == 0) {
956 /* Child */
957
958 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
959 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
960
961 if (!IN_SET(s[1], STDIN_FILENO, STDOUT_FILENO))
962 safe_close(s[1]);
963
964 (void) fd_cloexec(STDIN_FILENO, false);
965 (void) fd_cloexec(STDOUT_FILENO, false);
966 (void) fd_nonblock(STDIN_FILENO, false);
967 (void) fd_nonblock(STDOUT_FILENO, false);
968
969 if (b->exec_argv)
970 execvp(b->exec_path, b->exec_argv);
971 else {
972 const char *argv[] = { b->exec_path, NULL };
973 execvp(b->exec_path, (char**) argv);
974 }
975
976 _exit(EXIT_FAILURE);
977 }
978
979 safe_close(s[1]);
980 b->output_fd = b->input_fd = s[0];
981
982 bus_socket_setup(b);
983
984 return bus_socket_start_auth(b);
985 }
986
987 int bus_socket_take_fd(sd_bus *b) {
988 assert(b);
989
990 bus_socket_setup(b);
991
992 return bus_socket_start_auth(b);
993 }
994
995 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
996 struct iovec *iov;
997 ssize_t k;
998 size_t n;
999 unsigned j;
1000 int r;
1001
1002 assert(bus);
1003 assert(m);
1004 assert(idx);
1005 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1006
1007 if (*idx >= BUS_MESSAGE_SIZE(m))
1008 return 0;
1009
1010 r = bus_message_setup_iovec(m);
1011 if (r < 0)
1012 return r;
1013
1014 n = m->n_iovec * sizeof(struct iovec);
1015 iov = alloca(n);
1016 memcpy_safe(iov, m->iovec, n);
1017
1018 j = 0;
1019 iovec_advance(iov, &j, *idx);
1020
1021 if (bus->prefer_writev)
1022 k = writev(bus->output_fd, iov, m->n_iovec);
1023 else {
1024 struct msghdr mh = {
1025 .msg_iov = iov,
1026 .msg_iovlen = m->n_iovec,
1027 };
1028
1029 if (m->n_fds > 0 && *idx == 0) {
1030 struct cmsghdr *control;
1031
1032 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1033 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
1034 control->cmsg_level = SOL_SOCKET;
1035 control->cmsg_type = SCM_RIGHTS;
1036 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1037 }
1038
1039 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1040 if (k < 0 && errno == ENOTSOCK) {
1041 bus->prefer_writev = true;
1042 k = writev(bus->output_fd, iov, m->n_iovec);
1043 }
1044 }
1045
1046 if (k < 0)
1047 return errno == EAGAIN ? 0 : -errno;
1048
1049 *idx += (size_t) k;
1050 return 1;
1051 }
1052
1053 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1054 uint32_t a, b;
1055 uint8_t e;
1056 uint64_t sum;
1057
1058 assert(bus);
1059 assert(need);
1060 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1061
1062 if (bus->rbuffer_size < sizeof(struct bus_header)) {
1063 *need = sizeof(struct bus_header) + 8;
1064
1065 /* Minimum message size:
1066 *
1067 * Header +
1068 *
1069 * Method Call: +2 string headers
1070 * Signal: +3 string headers
1071 * Method Error: +1 string headers
1072 * +1 uint32 headers
1073 * Method Reply: +1 uint32 headers
1074 *
1075 * A string header is at least 9 bytes
1076 * A uint32 header is at least 8 bytes
1077 *
1078 * Hence the minimum message size of a valid message
1079 * is header + 8 bytes */
1080
1081 return 0;
1082 }
1083
1084 a = ((const uint32_t*) bus->rbuffer)[1];
1085 b = ((const uint32_t*) bus->rbuffer)[3];
1086
1087 e = ((const uint8_t*) bus->rbuffer)[0];
1088 if (e == BUS_LITTLE_ENDIAN) {
1089 a = le32toh(a);
1090 b = le32toh(b);
1091 } else if (e == BUS_BIG_ENDIAN) {
1092 a = be32toh(a);
1093 b = be32toh(b);
1094 } else
1095 return -EBADMSG;
1096
1097 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1098 if (sum >= BUS_MESSAGE_SIZE_MAX)
1099 return -ENOBUFS;
1100
1101 *need = (size_t) sum;
1102 return 0;
1103 }
1104
1105 static int bus_socket_make_message(sd_bus *bus, size_t size) {
1106 sd_bus_message *t;
1107 void *b;
1108 int r;
1109
1110 assert(bus);
1111 assert(bus->rbuffer_size >= size);
1112 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1113
1114 r = bus_rqueue_make_room(bus);
1115 if (r < 0)
1116 return r;
1117
1118 if (bus->rbuffer_size > size) {
1119 b = memdup((const uint8_t*) bus->rbuffer + size,
1120 bus->rbuffer_size - size);
1121 if (!b)
1122 return -ENOMEM;
1123 } else
1124 b = NULL;
1125
1126 r = bus_message_from_malloc(bus,
1127 bus->rbuffer, size,
1128 bus->fds, bus->n_fds,
1129 NULL,
1130 &t);
1131 if (r < 0) {
1132 free(b);
1133 return r;
1134 }
1135
1136 bus->rbuffer = b;
1137 bus->rbuffer_size -= size;
1138
1139 bus->fds = NULL;
1140 bus->n_fds = 0;
1141
1142 bus->rqueue[bus->rqueue_size++] = t;
1143
1144 return 1;
1145 }
1146
1147 int bus_socket_read_message(sd_bus *bus) {
1148 struct msghdr mh;
1149 struct iovec iov = {};
1150 ssize_t k;
1151 size_t need;
1152 int r;
1153 void *b;
1154 union {
1155 struct cmsghdr cmsghdr;
1156 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
1157 } control;
1158 bool handle_cmsg = false;
1159
1160 assert(bus);
1161 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1162
1163 r = bus_socket_read_message_need(bus, &need);
1164 if (r < 0)
1165 return r;
1166
1167 if (bus->rbuffer_size >= need)
1168 return bus_socket_make_message(bus, need);
1169
1170 b = realloc(bus->rbuffer, need);
1171 if (!b)
1172 return -ENOMEM;
1173
1174 bus->rbuffer = b;
1175
1176 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
1177 iov.iov_len = need - bus->rbuffer_size;
1178
1179 if (bus->prefer_readv)
1180 k = readv(bus->input_fd, &iov, 1);
1181 else {
1182 zero(mh);
1183 mh.msg_iov = &iov;
1184 mh.msg_iovlen = 1;
1185 mh.msg_control = &control;
1186 mh.msg_controllen = sizeof(control);
1187
1188 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
1189 if (k < 0 && errno == ENOTSOCK) {
1190 bus->prefer_readv = true;
1191 k = readv(bus->input_fd, &iov, 1);
1192 } else
1193 handle_cmsg = true;
1194 }
1195 if (k < 0)
1196 return errno == EAGAIN ? 0 : -errno;
1197 if (k == 0)
1198 return -ECONNRESET;
1199
1200 bus->rbuffer_size += k;
1201
1202 if (handle_cmsg) {
1203 struct cmsghdr *cmsg;
1204
1205 CMSG_FOREACH(cmsg, &mh)
1206 if (cmsg->cmsg_level == SOL_SOCKET &&
1207 cmsg->cmsg_type == SCM_RIGHTS) {
1208 int n, *f;
1209
1210 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1211
1212 if (!bus->can_fds) {
1213 /* Whut? We received fds but this
1214 * isn't actually enabled? Close them,
1215 * and fail */
1216
1217 close_many((int*) CMSG_DATA(cmsg), n);
1218 return -EIO;
1219 }
1220
1221 f = realloc(bus->fds, sizeof(int) * (bus->n_fds + n));
1222 if (!f) {
1223 close_many((int*) CMSG_DATA(cmsg), n);
1224 return -ENOMEM;
1225 }
1226
1227 memcpy_safe(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
1228 bus->fds = f;
1229 bus->n_fds += n;
1230 } else
1231 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1232 cmsg->cmsg_level, cmsg->cmsg_type);
1233 }
1234
1235 r = bus_socket_read_message_need(bus, &need);
1236 if (r < 0)
1237 return r;
1238
1239 if (bus->rbuffer_size >= need)
1240 return bus_socket_make_message(bus, need);
1241
1242 return 1;
1243 }
1244
1245 int bus_socket_process_opening(sd_bus *b) {
1246 int error = 0;
1247 socklen_t slen = sizeof(error);
1248 struct pollfd p = {
1249 .fd = b->output_fd,
1250 .events = POLLOUT,
1251 };
1252 int r;
1253
1254 assert(b->state == BUS_OPENING);
1255
1256 r = poll(&p, 1, 0);
1257 if (r < 0)
1258 return -errno;
1259
1260 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1261 return 0;
1262
1263 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1264 if (r < 0)
1265 b->last_connect_error = errno;
1266 else if (error != 0)
1267 b->last_connect_error = error;
1268 else if (p.revents & (POLLERR|POLLHUP))
1269 b->last_connect_error = ECONNREFUSED;
1270 else
1271 return bus_socket_start_auth(b);
1272
1273 return bus_next_address(b);
1274 }
1275
1276 int bus_socket_process_authenticating(sd_bus *b) {
1277 int r;
1278
1279 assert(b);
1280 assert(b->state == BUS_AUTHENTICATING);
1281
1282 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1283 return -ETIMEDOUT;
1284
1285 r = bus_socket_write_auth(b);
1286 if (r != 0)
1287 return r;
1288
1289 return bus_socket_read_auth(b);
1290 }
1291
1292 int bus_socket_process_watch_bind(sd_bus *b) {
1293 int r, q;
1294
1295 assert(b);
1296 assert(b->state == BUS_WATCH_BIND);
1297 assert(b->inotify_fd >= 0);
1298
1299 r = flush_fd(b->inotify_fd);
1300 if (r <= 0)
1301 return r;
1302
1303 log_debug("Got inotify event on bus %s.", strna(b->description));
1304
1305 /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1306 * to it again */
1307
1308 r = bus_socket_connect(b);
1309 if (r < 0)
1310 return r;
1311
1312 q = bus_attach_io_events(b);
1313 if (q < 0)
1314 return q;
1315
1316 q = bus_attach_inotify_event(b);
1317 if (q < 0)
1318 return q;
1319
1320 return r;
1321 }