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