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