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