1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2013 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include "sd-daemon.h"
32 #include "formats-util.h"
33 #include "signal-util.h"
36 #include "bus-socket.h"
37 #include "bus-internal.h"
38 #include "bus-message.h"
40 #define SNDBUF_SIZE (8*1024*1024)
42 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
45 struct iovec *i = iov + *idx;
47 if (i->iov_len > size) {
48 i->iov_base = (uint8_t*) i->iov_base + size;
62 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
67 m->iovec[m->n_iovec].iov_base = (void*) p;
68 m->iovec[m->n_iovec].iov_len = sz;
74 static int bus_message_setup_iovec(sd_bus_message *m) {
75 struct bus_body_part *part;
87 n = 1 + m->n_body_parts;
88 if (n < ELEMENTSOF(m->iovec_fixed))
89 m->iovec = m->iovec_fixed;
91 m->iovec = new(struct iovec, n);
98 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
102 MESSAGE_FOREACH_PART(part, i, m) {
103 r = bus_body_part_map(part);
107 r = append_iovec(m, part->data, part->size);
112 assert(n == m->n_iovec);
121 bool bus_socket_auth_needs_write(sd_bus *b) {
125 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
128 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
129 struct iovec *j = b->auth_iovec + i;
138 static int bus_socket_write_auth(sd_bus *b) {
142 assert(b->state == BUS_AUTHENTICATING);
144 if (!bus_socket_auth_needs_write(b))
147 if (b->prefer_writev)
148 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
153 mh.msg_iov = b->auth_iovec + b->auth_index;
154 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
156 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
157 if (k < 0 && errno == ENOTSOCK) {
158 b->prefer_writev = true;
159 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
164 return errno == EAGAIN ? 0 : -errno;
166 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
170 static int bus_socket_auth_verify_client(sd_bus *b) {
178 /* We expect two response lines: "OK" and possibly
181 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
185 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD) {
186 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
196 /* Nice! We got all the lines we need. First check the OK
199 if (e - (char*) b->rbuffer != 3 + 32)
202 if (memcmp(b->rbuffer, "OK ", 3))
205 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
207 for (i = 0; i < 32; i += 2) {
210 x = unhexchar(((char*) b->rbuffer)[3 + i]);
211 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
216 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
219 if (!sd_id128_equal(b->server_id, SD_ID128_NULL) &&
220 !sd_id128_equal(b->server_id, peer))
225 /* And possibly check the second line, too */
229 (f - e == strlen("\r\nAGREE_UNIX_FD")) &&
230 memcmp(e + 2, "AGREE_UNIX_FD", strlen("AGREE_UNIX_FD")) == 0;
232 b->rbuffer_size -= (start - (char*) b->rbuffer);
233 memmove(b->rbuffer, start, b->rbuffer_size);
235 r = bus_start_running(b);
242 static bool line_equals(const char *s, size_t m, const char *line) {
249 return memcmp(s, line, l) == 0;
252 static bool line_begins(const char *s, size_t m, const char *word) {
259 if (memcmp(s, word, l) != 0)
262 return m == l || (m > l && s[l] == ' ');
265 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
266 _cleanup_free_ char *token = NULL;
268 if (!b->anonymous_auth)
279 token = unhexmem(p, l);
283 if (memchr(token, 0, l/2))
286 return !!utf8_is_valid(token);
289 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
290 _cleanup_free_ char *token = NULL;
294 /* We don't do any real authentication here. Instead, we if
295 * the owner of this bus wanted authentication he should have
296 * checked SO_PEERCRED before even creating the bus object. */
298 if (!b->anonymous_auth && !b->ucred_valid)
310 token = unhexmem(p, l);
314 if (memchr(token, 0, l/2))
317 r = parse_uid(token, &u);
321 /* We ignore the passed value if anonymous authentication is
323 if (!b->anonymous_auth && u != b->ucred.uid)
329 static int bus_socket_auth_write(sd_bus *b, const char *t) {
336 /* We only make use of the first iovec */
337 assert(b->auth_index == 0 || b->auth_index == 1);
340 p = malloc(b->auth_iovec[0].iov_len + l);
344 memcpy(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
345 memcpy(p + b->auth_iovec[0].iov_len, t, l);
347 b->auth_iovec[0].iov_base = p;
348 b->auth_iovec[0].iov_len += l;
350 free(b->auth_buffer);
356 static int bus_socket_auth_write_ok(sd_bus *b) {
357 char t[3 + 32 + 2 + 1];
361 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
363 return bus_socket_auth_write(b, t);
366 static int bus_socket_auth_verify_server(sd_bus *b) {
370 bool processed = false;
375 if (b->rbuffer_size < 1)
378 /* First char must be a NUL byte */
379 if (*(char*) b->rbuffer != 0)
382 if (b->rbuffer_size < 3)
385 /* Begin with the first line */
386 if (b->auth_rbegin <= 0)
390 /* Check if line is complete */
391 line = (char*) b->rbuffer + b->auth_rbegin;
392 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
398 if (line_begins(line, l, "AUTH ANONYMOUS")) {
400 r = verify_anonymous_token(b, line + 14, l - 14);
404 r = bus_socket_auth_write(b, "REJECTED\r\n");
406 b->auth = BUS_AUTH_ANONYMOUS;
407 r = bus_socket_auth_write_ok(b);
410 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
412 r = verify_external_token(b, line + 13, l - 13);
416 r = bus_socket_auth_write(b, "REJECTED\r\n");
418 b->auth = BUS_AUTH_EXTERNAL;
419 r = bus_socket_auth_write_ok(b);
422 } else if (line_begins(line, l, "AUTH"))
423 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
424 else if (line_equals(line, l, "CANCEL") ||
425 line_begins(line, l, "ERROR")) {
427 b->auth = _BUS_AUTH_INVALID;
428 r = bus_socket_auth_write(b, "REJECTED\r\n");
430 } else if (line_equals(line, l, "BEGIN")) {
432 if (b->auth == _BUS_AUTH_INVALID)
433 r = bus_socket_auth_write(b, "ERROR\r\n");
435 /* We can't leave from the auth phase
436 * before we haven't written
437 * everything queued, so let's check
440 if (bus_socket_auth_needs_write(b))
443 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
444 memmove(b->rbuffer, e + 2, b->rbuffer_size);
445 return bus_start_running(b);
448 } else if (line_begins(line, l, "DATA")) {
450 if (b->auth == _BUS_AUTH_INVALID)
451 r = bus_socket_auth_write(b, "ERROR\r\n");
453 if (b->auth == BUS_AUTH_ANONYMOUS)
454 r = verify_anonymous_token(b, line + 4, l - 4);
456 r = verify_external_token(b, line + 4, l - 4);
461 b->auth = _BUS_AUTH_INVALID;
462 r = bus_socket_auth_write(b, "REJECTED\r\n");
464 r = bus_socket_auth_write_ok(b);
466 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
467 if (b->auth == _BUS_AUTH_INVALID || !(b->hello_flags & KDBUS_HELLO_ACCEPT_FD))
468 r = bus_socket_auth_write(b, "ERROR\r\n");
471 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
474 r = bus_socket_auth_write(b, "ERROR\r\n");
479 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
485 static int bus_socket_auth_verify(sd_bus *b) {
489 return bus_socket_auth_verify_server(b);
491 return bus_socket_auth_verify_client(b);
494 static int bus_socket_read_auth(sd_bus *b) {
496 struct iovec iov = {};
502 struct cmsghdr cmsghdr;
503 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
505 struct cmsghdr *cmsg;
506 bool handle_cmsg = false;
509 assert(b->state == BUS_AUTHENTICATING);
511 r = bus_socket_auth_verify(b);
515 n = MAX(256u, b->rbuffer_size * 2);
517 if (n > BUS_AUTH_SIZE_MAX)
518 n = BUS_AUTH_SIZE_MAX;
520 if (b->rbuffer_size >= n)
523 p = realloc(b->rbuffer, n);
529 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
530 iov.iov_len = n - b->rbuffer_size;
533 k = readv(b->input_fd, &iov, 1);
538 mh.msg_control = &control;
539 mh.msg_controllen = sizeof(control);
541 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
542 if (k < 0 && errno == ENOTSOCK) {
543 b->prefer_readv = true;
544 k = readv(b->input_fd, &iov, 1);
549 return errno == EAGAIN ? 0 : -errno;
553 b->rbuffer_size += k;
556 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
557 if (cmsg->cmsg_level == SOL_SOCKET &&
558 cmsg->cmsg_type == SCM_RIGHTS) {
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);
568 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
569 cmsg->cmsg_level, cmsg->cmsg_type);
571 r = bus_socket_auth_verify(b);
578 void bus_socket_setup(sd_bus *b) {
581 /* Increase the buffers to 8 MB */
582 fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
583 fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
585 b->is_kernel = false;
586 b->message_version = 1;
587 b->message_endian = 0;
590 static void bus_get_peercred(sd_bus *b) {
595 /* Get the peer for socketpair() sockets */
596 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
598 /* Get the SELinux context of the peer */
599 r = getpeersec(b->input_fd, &b->label);
600 if (r < 0 && r != -EOPNOTSUPP)
601 log_debug_errno(r, "Failed to determine peer security context: %m");
604 static int bus_socket_start_auth_client(sd_bus *b) {
606 const char *auth_suffix, *auth_prefix;
610 if (b->anonymous_auth) {
611 auth_prefix = "\0AUTH ANONYMOUS ";
613 /* For ANONYMOUS auth we send some arbitrary "trace" string */
615 b->auth_buffer = hexmem("anonymous", l);
617 char text[DECIMAL_STR_MAX(uid_t) + 1];
619 auth_prefix = "\0AUTH EXTERNAL ";
621 xsprintf(text, UID_FMT, geteuid());
624 b->auth_buffer = hexmem(text, l);
630 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD)
631 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
633 auth_suffix = "\r\nBEGIN\r\n";
635 b->auth_iovec[0].iov_base = (void*) auth_prefix;
636 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
637 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
638 b->auth_iovec[1].iov_len = l * 2;
639 b->auth_iovec[2].iov_base = (void*) auth_suffix;
640 b->auth_iovec[2].iov_len = strlen(auth_suffix);
642 return bus_socket_write_auth(b);
645 int bus_socket_start_auth(sd_bus *b) {
650 b->state = BUS_AUTHENTICATING;
651 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_DEFAULT_TIMEOUT;
653 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
654 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
656 if (b->output_fd != b->input_fd)
657 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
658 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
661 return bus_socket_read_auth(b);
663 return bus_socket_start_auth_client(b);
666 int bus_socket_connect(sd_bus *b) {
670 assert(b->input_fd < 0);
671 assert(b->output_fd < 0);
672 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
674 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
678 b->output_fd = b->input_fd;
682 r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
684 if (errno == EINPROGRESS)
690 return bus_socket_start_auth(b);
693 int bus_socket_exec(sd_bus *b) {
698 assert(b->input_fd < 0);
699 assert(b->output_fd < 0);
700 assert(b->exec_path);
702 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
714 (void) reset_all_signal_handlers();
715 (void) reset_signal_mask();
717 close_all_fds(s+1, 1);
719 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
720 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
722 if (s[1] != STDIN_FILENO && s[1] != STDOUT_FILENO)
725 fd_cloexec(STDIN_FILENO, false);
726 fd_cloexec(STDOUT_FILENO, false);
727 fd_nonblock(STDIN_FILENO, false);
728 fd_nonblock(STDOUT_FILENO, false);
731 execvp(b->exec_path, b->exec_argv);
733 const char *argv[] = { b->exec_path, NULL };
734 execvp(b->exec_path, (char**) argv);
741 b->output_fd = b->input_fd = s[0];
745 return bus_socket_start_auth(b);
748 int bus_socket_take_fd(sd_bus *b) {
753 return bus_socket_start_auth(b);
756 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
766 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
768 if (*idx >= BUS_MESSAGE_SIZE(m))
771 r = bus_message_setup_iovec(m);
775 n = m->n_iovec * sizeof(struct iovec);
777 memcpy(iov, m->iovec, n);
780 iovec_advance(iov, &j, *idx);
782 if (bus->prefer_writev)
783 k = writev(bus->output_fd, iov, m->n_iovec);
787 .msg_iovlen = m->n_iovec,
791 struct cmsghdr *control;
793 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
794 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
795 control->cmsg_level = SOL_SOCKET;
796 control->cmsg_type = SCM_RIGHTS;
797 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
800 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
801 if (k < 0 && errno == ENOTSOCK) {
802 bus->prefer_writev = true;
803 k = writev(bus->output_fd, iov, m->n_iovec);
808 return errno == EAGAIN ? 0 : -errno;
814 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
821 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
823 if (bus->rbuffer_size < sizeof(struct bus_header)) {
824 *need = sizeof(struct bus_header) + 8;
826 /* Minimum message size:
830 * Method Call: +2 string headers
831 * Signal: +3 string headers
832 * Method Error: +1 string headers
834 * Method Reply: +1 uint32 headers
836 * A string header is at least 9 bytes
837 * A uint32 header is at least 8 bytes
839 * Hence the minimum message size of a valid message
840 * is header + 8 bytes */
845 a = ((const uint32_t*) bus->rbuffer)[1];
846 b = ((const uint32_t*) bus->rbuffer)[3];
848 e = ((const uint8_t*) bus->rbuffer)[0];
849 if (e == BUS_LITTLE_ENDIAN) {
852 } else if (e == BUS_BIG_ENDIAN) {
858 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
859 if (sum >= BUS_MESSAGE_SIZE_MAX)
862 *need = (size_t) sum;
866 static int bus_socket_make_message(sd_bus *bus, size_t size) {
872 assert(bus->rbuffer_size >= size);
873 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
875 r = bus_rqueue_make_room(bus);
879 if (bus->rbuffer_size > size) {
880 b = memdup((const uint8_t*) bus->rbuffer + size,
881 bus->rbuffer_size - size);
887 r = bus_message_from_malloc(bus,
889 bus->fds, bus->n_fds,
899 bus->rbuffer_size -= size;
904 bus->rqueue[bus->rqueue_size++] = t;
909 int bus_socket_read_message(sd_bus *bus) {
911 struct iovec iov = {};
917 struct cmsghdr cmsghdr;
918 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
920 struct cmsghdr *cmsg;
921 bool handle_cmsg = false;
924 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
926 r = bus_socket_read_message_need(bus, &need);
930 if (bus->rbuffer_size >= need)
931 return bus_socket_make_message(bus, need);
933 b = realloc(bus->rbuffer, need);
939 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
940 iov.iov_len = need - bus->rbuffer_size;
942 if (bus->prefer_readv)
943 k = readv(bus->input_fd, &iov, 1);
948 mh.msg_control = &control;
949 mh.msg_controllen = sizeof(control);
951 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
952 if (k < 0 && errno == ENOTSOCK) {
953 bus->prefer_readv = true;
954 k = readv(bus->input_fd, &iov, 1);
959 return errno == EAGAIN ? 0 : -errno;
963 bus->rbuffer_size += k;
966 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
967 if (cmsg->cmsg_level == SOL_SOCKET &&
968 cmsg->cmsg_type == SCM_RIGHTS) {
971 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
974 /* Whut? We received fds but this
975 * isn't actually enabled? Close them,
978 close_many((int*) CMSG_DATA(cmsg), n);
982 f = realloc(bus->fds, sizeof(int) + (bus->n_fds + n));
984 close_many((int*) CMSG_DATA(cmsg), n);
988 memcpy(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
992 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
993 cmsg->cmsg_level, cmsg->cmsg_type);
995 r = bus_socket_read_message_need(bus, &need);
999 if (bus->rbuffer_size >= need)
1000 return bus_socket_make_message(bus, need);
1005 int bus_socket_process_opening(sd_bus *b) {
1007 socklen_t slen = sizeof(error);
1014 assert(b->state == BUS_OPENING);
1020 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1023 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1025 b->last_connect_error = errno;
1026 else if (error != 0)
1027 b->last_connect_error = error;
1028 else if (p.revents & (POLLERR|POLLHUP))
1029 b->last_connect_error = ECONNREFUSED;
1031 return bus_socket_start_auth(b);
1033 return bus_next_address(b);
1036 int bus_socket_process_authenticating(sd_bus *b) {
1040 assert(b->state == BUS_AUTHENTICATING);
1042 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1045 r = bus_socket_write_auth(b);
1049 return bus_socket_read_auth(b);