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/>.
28 #include "sd-daemon.h"
30 #include "alloc-util.h"
31 #include "bus-internal.h"
32 #include "bus-message.h"
33 #include "bus-socket.h"
35 #include "formats-util.h"
36 #include "hexdecoct.h"
39 #include "selinux-util.h"
40 #include "signal-util.h"
41 #include "stdio-util.h"
42 #include "string-util.h"
43 #include "user-util.h"
47 #define SNDBUF_SIZE (8*1024*1024)
49 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
52 struct iovec *i = iov + *idx;
54 if (i->iov_len > size) {
55 i->iov_base = (uint8_t*) i->iov_base + size;
69 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
74 m->iovec[m->n_iovec].iov_base = (void*) p;
75 m->iovec[m->n_iovec].iov_len = sz;
81 static int bus_message_setup_iovec(sd_bus_message *m) {
82 struct bus_body_part *part;
94 n = 1 + m->n_body_parts;
95 if (n < ELEMENTSOF(m->iovec_fixed))
96 m->iovec = m->iovec_fixed;
98 m->iovec = new(struct iovec, n);
105 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
109 MESSAGE_FOREACH_PART(part, i, m) {
110 r = bus_body_part_map(part);
114 r = append_iovec(m, part->data, part->size);
119 assert(n == m->n_iovec);
128 bool bus_socket_auth_needs_write(sd_bus *b) {
132 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
135 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
136 struct iovec *j = b->auth_iovec + i;
145 static int bus_socket_write_auth(sd_bus *b) {
149 assert(b->state == BUS_AUTHENTICATING);
151 if (!bus_socket_auth_needs_write(b))
154 if (b->prefer_writev)
155 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
160 mh.msg_iov = b->auth_iovec + b->auth_index;
161 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
163 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
164 if (k < 0 && errno == ENOTSOCK) {
165 b->prefer_writev = true;
166 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
171 return errno == EAGAIN ? 0 : -errno;
173 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
177 static int bus_socket_auth_verify_client(sd_bus *b) {
185 /* We expect two response lines: "OK" and possibly
188 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
192 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD) {
193 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
203 /* Nice! We got all the lines we need. First check the OK
206 if (e - (char*) b->rbuffer != 3 + 32)
209 if (memcmp(b->rbuffer, "OK ", 3))
212 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
214 for (i = 0; i < 32; i += 2) {
217 x = unhexchar(((char*) b->rbuffer)[3 + i]);
218 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
223 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
226 if (!sd_id128_equal(b->server_id, SD_ID128_NULL) &&
227 !sd_id128_equal(b->server_id, peer))
232 /* And possibly check the second line, too */
236 (f - e == strlen("\r\nAGREE_UNIX_FD")) &&
237 memcmp(e + 2, "AGREE_UNIX_FD", strlen("AGREE_UNIX_FD")) == 0;
239 b->rbuffer_size -= (start - (char*) b->rbuffer);
240 memmove(b->rbuffer, start, b->rbuffer_size);
242 r = bus_start_running(b);
249 static bool line_equals(const char *s, size_t m, const char *line) {
256 return memcmp(s, line, l) == 0;
259 static bool line_begins(const char *s, size_t m, const char *word) {
266 if (memcmp(s, word, l) != 0)
269 return m == l || (m > l && s[l] == ' ');
272 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
273 _cleanup_free_ char *token = NULL;
277 if (!b->anonymous_auth)
289 r = unhexmem(p, l, (void **) &token, &len);
293 if (memchr(token, 0, len))
296 return !!utf8_is_valid(token);
299 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
300 _cleanup_free_ char *token = NULL;
305 /* We don't do any real authentication here. Instead, we if
306 * the owner of this bus wanted authentication he should have
307 * checked SO_PEERCRED before even creating the bus object. */
309 if (!b->anonymous_auth && !b->ucred_valid)
321 r = unhexmem(p, l, (void**) &token, &len);
325 if (memchr(token, 0, len))
328 r = parse_uid(token, &u);
332 /* We ignore the passed value if anonymous authentication is
334 if (!b->anonymous_auth && u != b->ucred.uid)
340 static int bus_socket_auth_write(sd_bus *b, const char *t) {
347 /* We only make use of the first iovec */
348 assert(b->auth_index == 0 || b->auth_index == 1);
351 p = malloc(b->auth_iovec[0].iov_len + l);
355 memcpy(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
356 memcpy(p + b->auth_iovec[0].iov_len, t, l);
358 b->auth_iovec[0].iov_base = p;
359 b->auth_iovec[0].iov_len += l;
361 free(b->auth_buffer);
367 static int bus_socket_auth_write_ok(sd_bus *b) {
368 char t[3 + 32 + 2 + 1];
372 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
374 return bus_socket_auth_write(b, t);
377 static int bus_socket_auth_verify_server(sd_bus *b) {
381 bool processed = false;
386 if (b->rbuffer_size < 1)
389 /* First char must be a NUL byte */
390 if (*(char*) b->rbuffer != 0)
393 if (b->rbuffer_size < 3)
396 /* Begin with the first line */
397 if (b->auth_rbegin <= 0)
401 /* Check if line is complete */
402 line = (char*) b->rbuffer + b->auth_rbegin;
403 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
409 if (line_begins(line, l, "AUTH ANONYMOUS")) {
411 r = verify_anonymous_token(b, line + 14, l - 14);
415 r = bus_socket_auth_write(b, "REJECTED\r\n");
417 b->auth = BUS_AUTH_ANONYMOUS;
418 r = bus_socket_auth_write_ok(b);
421 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
423 r = verify_external_token(b, line + 13, l - 13);
427 r = bus_socket_auth_write(b, "REJECTED\r\n");
429 b->auth = BUS_AUTH_EXTERNAL;
430 r = bus_socket_auth_write_ok(b);
433 } else if (line_begins(line, l, "AUTH"))
434 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
435 else if (line_equals(line, l, "CANCEL") ||
436 line_begins(line, l, "ERROR")) {
438 b->auth = _BUS_AUTH_INVALID;
439 r = bus_socket_auth_write(b, "REJECTED\r\n");
441 } else if (line_equals(line, l, "BEGIN")) {
443 if (b->auth == _BUS_AUTH_INVALID)
444 r = bus_socket_auth_write(b, "ERROR\r\n");
446 /* We can't leave from the auth phase
447 * before we haven't written
448 * everything queued, so let's check
451 if (bus_socket_auth_needs_write(b))
454 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
455 memmove(b->rbuffer, e + 2, b->rbuffer_size);
456 return bus_start_running(b);
459 } else if (line_begins(line, l, "DATA")) {
461 if (b->auth == _BUS_AUTH_INVALID)
462 r = bus_socket_auth_write(b, "ERROR\r\n");
464 if (b->auth == BUS_AUTH_ANONYMOUS)
465 r = verify_anonymous_token(b, line + 4, l - 4);
467 r = verify_external_token(b, line + 4, l - 4);
472 b->auth = _BUS_AUTH_INVALID;
473 r = bus_socket_auth_write(b, "REJECTED\r\n");
475 r = bus_socket_auth_write_ok(b);
477 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
478 if (b->auth == _BUS_AUTH_INVALID || !(b->hello_flags & KDBUS_HELLO_ACCEPT_FD))
479 r = bus_socket_auth_write(b, "ERROR\r\n");
482 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
485 r = bus_socket_auth_write(b, "ERROR\r\n");
490 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
496 static int bus_socket_auth_verify(sd_bus *b) {
500 return bus_socket_auth_verify_server(b);
502 return bus_socket_auth_verify_client(b);
505 static int bus_socket_read_auth(sd_bus *b) {
507 struct iovec iov = {};
513 struct cmsghdr cmsghdr;
514 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
516 bool handle_cmsg = false;
519 assert(b->state == BUS_AUTHENTICATING);
521 r = bus_socket_auth_verify(b);
525 n = MAX(256u, b->rbuffer_size * 2);
527 if (n > BUS_AUTH_SIZE_MAX)
528 n = BUS_AUTH_SIZE_MAX;
530 if (b->rbuffer_size >= n)
533 p = realloc(b->rbuffer, n);
539 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
540 iov.iov_len = n - b->rbuffer_size;
543 k = readv(b->input_fd, &iov, 1);
548 mh.msg_control = &control;
549 mh.msg_controllen = sizeof(control);
551 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
552 if (k < 0 && errno == ENOTSOCK) {
553 b->prefer_readv = true;
554 k = readv(b->input_fd, &iov, 1);
559 return errno == EAGAIN ? 0 : -errno;
563 b->rbuffer_size += k;
566 struct cmsghdr *cmsg;
568 CMSG_FOREACH(cmsg, &mh)
569 if (cmsg->cmsg_level == SOL_SOCKET &&
570 cmsg->cmsg_type == SCM_RIGHTS) {
573 /* Whut? We received fds during the auth
574 * protocol? Somebody is playing games with
575 * us. Close them all, and fail */
576 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
577 close_many((int*) CMSG_DATA(cmsg), j);
580 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
581 cmsg->cmsg_level, cmsg->cmsg_type);
584 r = bus_socket_auth_verify(b);
591 void bus_socket_setup(sd_bus *b) {
594 /* Increase the buffers to 8 MB */
595 fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
596 fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
598 b->is_kernel = false;
599 b->message_version = 1;
600 b->message_endian = 0;
603 static void bus_get_peercred(sd_bus *b) {
608 /* Get the peer for socketpair() sockets */
609 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
611 /* Get the SELinux context of the peer */
612 if (mac_selinux_use()) {
613 r = getpeersec(b->input_fd, &b->label);
614 if (r < 0 && r != -EOPNOTSUPP)
615 log_debug_errno(r, "Failed to determine peer security context: %m");
619 static int bus_socket_start_auth_client(sd_bus *b) {
621 const char *auth_suffix, *auth_prefix;
625 if (b->anonymous_auth) {
626 auth_prefix = "\0AUTH ANONYMOUS ";
628 /* For ANONYMOUS auth we send some arbitrary "trace" string */
630 b->auth_buffer = hexmem("anonymous", l);
632 char text[DECIMAL_STR_MAX(uid_t) + 1];
634 auth_prefix = "\0AUTH EXTERNAL ";
636 xsprintf(text, UID_FMT, geteuid());
639 b->auth_buffer = hexmem(text, l);
645 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD)
646 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
648 auth_suffix = "\r\nBEGIN\r\n";
650 b->auth_iovec[0].iov_base = (void*) auth_prefix;
651 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
652 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
653 b->auth_iovec[1].iov_len = l * 2;
654 b->auth_iovec[2].iov_base = (void*) auth_suffix;
655 b->auth_iovec[2].iov_len = strlen(auth_suffix);
657 return bus_socket_write_auth(b);
660 int bus_socket_start_auth(sd_bus *b) {
665 b->state = BUS_AUTHENTICATING;
666 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_DEFAULT_TIMEOUT;
668 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
669 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
671 if (b->output_fd != b->input_fd)
672 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
673 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
676 return bus_socket_read_auth(b);
678 return bus_socket_start_auth_client(b);
681 int bus_socket_connect(sd_bus *b) {
685 assert(b->input_fd < 0);
686 assert(b->output_fd < 0);
687 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
689 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
693 b->output_fd = b->input_fd;
697 r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
699 if (errno == EINPROGRESS)
705 return bus_socket_start_auth(b);
708 int bus_socket_exec(sd_bus *b) {
713 assert(b->input_fd < 0);
714 assert(b->output_fd < 0);
715 assert(b->exec_path);
717 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
729 (void) reset_all_signal_handlers();
730 (void) reset_signal_mask();
732 close_all_fds(s+1, 1);
734 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
735 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
737 if (s[1] != STDIN_FILENO && s[1] != STDOUT_FILENO)
740 fd_cloexec(STDIN_FILENO, false);
741 fd_cloexec(STDOUT_FILENO, false);
742 fd_nonblock(STDIN_FILENO, false);
743 fd_nonblock(STDOUT_FILENO, false);
746 execvp(b->exec_path, b->exec_argv);
748 const char *argv[] = { b->exec_path, NULL };
749 execvp(b->exec_path, (char**) argv);
756 b->output_fd = b->input_fd = s[0];
760 return bus_socket_start_auth(b);
763 int bus_socket_take_fd(sd_bus *b) {
768 return bus_socket_start_auth(b);
771 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
781 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
783 if (*idx >= BUS_MESSAGE_SIZE(m))
786 r = bus_message_setup_iovec(m);
790 n = m->n_iovec * sizeof(struct iovec);
792 memcpy(iov, m->iovec, n);
795 iovec_advance(iov, &j, *idx);
797 if (bus->prefer_writev)
798 k = writev(bus->output_fd, iov, m->n_iovec);
802 .msg_iovlen = m->n_iovec,
806 struct cmsghdr *control;
808 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
809 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
810 control->cmsg_level = SOL_SOCKET;
811 control->cmsg_type = SCM_RIGHTS;
812 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
815 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
816 if (k < 0 && errno == ENOTSOCK) {
817 bus->prefer_writev = true;
818 k = writev(bus->output_fd, iov, m->n_iovec);
823 return errno == EAGAIN ? 0 : -errno;
829 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
836 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
838 if (bus->rbuffer_size < sizeof(struct bus_header)) {
839 *need = sizeof(struct bus_header) + 8;
841 /* Minimum message size:
845 * Method Call: +2 string headers
846 * Signal: +3 string headers
847 * Method Error: +1 string headers
849 * Method Reply: +1 uint32 headers
851 * A string header is at least 9 bytes
852 * A uint32 header is at least 8 bytes
854 * Hence the minimum message size of a valid message
855 * is header + 8 bytes */
860 a = ((const uint32_t*) bus->rbuffer)[1];
861 b = ((const uint32_t*) bus->rbuffer)[3];
863 e = ((const uint8_t*) bus->rbuffer)[0];
864 if (e == BUS_LITTLE_ENDIAN) {
867 } else if (e == BUS_BIG_ENDIAN) {
873 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
874 if (sum >= BUS_MESSAGE_SIZE_MAX)
877 *need = (size_t) sum;
881 static int bus_socket_make_message(sd_bus *bus, size_t size) {
887 assert(bus->rbuffer_size >= size);
888 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
890 r = bus_rqueue_make_room(bus);
894 if (bus->rbuffer_size > size) {
895 b = memdup((const uint8_t*) bus->rbuffer + size,
896 bus->rbuffer_size - size);
902 r = bus_message_from_malloc(bus,
904 bus->fds, bus->n_fds,
913 bus->rbuffer_size -= size;
918 bus->rqueue[bus->rqueue_size++] = t;
923 int bus_socket_read_message(sd_bus *bus) {
925 struct iovec iov = {};
931 struct cmsghdr cmsghdr;
932 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
934 bool handle_cmsg = false;
937 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
939 r = bus_socket_read_message_need(bus, &need);
943 if (bus->rbuffer_size >= need)
944 return bus_socket_make_message(bus, need);
946 b = realloc(bus->rbuffer, need);
952 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
953 iov.iov_len = need - bus->rbuffer_size;
955 if (bus->prefer_readv)
956 k = readv(bus->input_fd, &iov, 1);
961 mh.msg_control = &control;
962 mh.msg_controllen = sizeof(control);
964 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
965 if (k < 0 && errno == ENOTSOCK) {
966 bus->prefer_readv = true;
967 k = readv(bus->input_fd, &iov, 1);
972 return errno == EAGAIN ? 0 : -errno;
976 bus->rbuffer_size += k;
979 struct cmsghdr *cmsg;
981 CMSG_FOREACH(cmsg, &mh)
982 if (cmsg->cmsg_level == SOL_SOCKET &&
983 cmsg->cmsg_type == SCM_RIGHTS) {
986 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
989 /* Whut? We received fds but this
990 * isn't actually enabled? Close them,
993 close_many((int*) CMSG_DATA(cmsg), n);
997 f = realloc(bus->fds, sizeof(int) * (bus->n_fds + n));
999 close_many((int*) CMSG_DATA(cmsg), n);
1003 memcpy(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
1007 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1008 cmsg->cmsg_level, cmsg->cmsg_type);
1011 r = bus_socket_read_message_need(bus, &need);
1015 if (bus->rbuffer_size >= need)
1016 return bus_socket_make_message(bus, need);
1021 int bus_socket_process_opening(sd_bus *b) {
1023 socklen_t slen = sizeof(error);
1030 assert(b->state == BUS_OPENING);
1036 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1039 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1041 b->last_connect_error = errno;
1042 else if (error != 0)
1043 b->last_connect_error = error;
1044 else if (p.revents & (POLLERR|POLLHUP))
1045 b->last_connect_error = ECONNREFUSED;
1047 return bus_socket_start_auth(b);
1049 return bus_next_address(b);
1052 int bus_socket_process_authenticating(sd_bus *b) {
1056 assert(b->state == BUS_AUTHENTICATING);
1058 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1061 r = bus_socket_write_auth(b);
1065 return bus_socket_read_auth(b);