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) {
593 /* Get the peer for socketpair() sockets */
594 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
597 static int bus_socket_start_auth_client(sd_bus *b) {
599 const char *auth_suffix, *auth_prefix;
603 if (b->anonymous_auth) {
604 auth_prefix = "\0AUTH ANONYMOUS ";
606 /* For ANONYMOUS auth we send some arbitrary "trace" string */
608 b->auth_buffer = hexmem("anonymous", l);
610 char text[DECIMAL_STR_MAX(uid_t) + 1];
612 auth_prefix = "\0AUTH EXTERNAL ";
614 xsprintf(text, UID_FMT, geteuid());
617 b->auth_buffer = hexmem(text, l);
623 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD)
624 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
626 auth_suffix = "\r\nBEGIN\r\n";
628 b->auth_iovec[0].iov_base = (void*) auth_prefix;
629 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
630 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
631 b->auth_iovec[1].iov_len = l * 2;
632 b->auth_iovec[2].iov_base = (void*) auth_suffix;
633 b->auth_iovec[2].iov_len = strlen(auth_suffix);
635 return bus_socket_write_auth(b);
638 int bus_socket_start_auth(sd_bus *b) {
643 b->state = BUS_AUTHENTICATING;
644 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_DEFAULT_TIMEOUT;
646 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
647 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
649 if (b->output_fd != b->input_fd)
650 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
651 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
654 return bus_socket_read_auth(b);
656 return bus_socket_start_auth_client(b);
659 int bus_socket_connect(sd_bus *b) {
663 assert(b->input_fd < 0);
664 assert(b->output_fd < 0);
665 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
667 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
671 b->output_fd = b->input_fd;
675 r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
677 if (errno == EINPROGRESS)
683 return bus_socket_start_auth(b);
686 int bus_socket_exec(sd_bus *b) {
691 assert(b->input_fd < 0);
692 assert(b->output_fd < 0);
693 assert(b->exec_path);
695 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
707 (void) reset_all_signal_handlers();
708 (void) reset_signal_mask();
710 close_all_fds(s+1, 1);
712 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
713 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
715 if (s[1] != STDIN_FILENO && s[1] != STDOUT_FILENO)
718 fd_cloexec(STDIN_FILENO, false);
719 fd_cloexec(STDOUT_FILENO, false);
720 fd_nonblock(STDIN_FILENO, false);
721 fd_nonblock(STDOUT_FILENO, false);
724 execvp(b->exec_path, b->exec_argv);
726 const char *argv[] = { b->exec_path, NULL };
727 execvp(b->exec_path, (char**) argv);
734 b->output_fd = b->input_fd = s[0];
738 return bus_socket_start_auth(b);
741 int bus_socket_take_fd(sd_bus *b) {
746 return bus_socket_start_auth(b);
749 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
759 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
761 if (*idx >= BUS_MESSAGE_SIZE(m))
764 r = bus_message_setup_iovec(m);
768 n = m->n_iovec * sizeof(struct iovec);
770 memcpy(iov, m->iovec, n);
773 iovec_advance(iov, &j, *idx);
775 if (bus->prefer_writev)
776 k = writev(bus->output_fd, iov, m->n_iovec);
780 .msg_iovlen = m->n_iovec,
784 struct cmsghdr *control;
786 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
787 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
788 control->cmsg_level = SOL_SOCKET;
789 control->cmsg_type = SCM_RIGHTS;
790 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
793 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
794 if (k < 0 && errno == ENOTSOCK) {
795 bus->prefer_writev = true;
796 k = writev(bus->output_fd, iov, m->n_iovec);
801 return errno == EAGAIN ? 0 : -errno;
807 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
814 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
816 if (bus->rbuffer_size < sizeof(struct bus_header)) {
817 *need = sizeof(struct bus_header) + 8;
819 /* Minimum message size:
823 * Method Call: +2 string headers
824 * Signal: +3 string headers
825 * Method Error: +1 string headers
827 * Method Reply: +1 uint32 headers
829 * A string header is at least 9 bytes
830 * A uint32 header is at least 8 bytes
832 * Hence the minimum message size of a valid message
833 * is header + 8 bytes */
838 a = ((const uint32_t*) bus->rbuffer)[1];
839 b = ((const uint32_t*) bus->rbuffer)[3];
841 e = ((const uint8_t*) bus->rbuffer)[0];
842 if (e == BUS_LITTLE_ENDIAN) {
845 } else if (e == BUS_BIG_ENDIAN) {
851 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
852 if (sum >= BUS_MESSAGE_SIZE_MAX)
855 *need = (size_t) sum;
859 static int bus_socket_make_message(sd_bus *bus, size_t size) {
865 assert(bus->rbuffer_size >= size);
866 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
868 r = bus_rqueue_make_room(bus);
872 if (bus->rbuffer_size > size) {
873 b = memdup((const uint8_t*) bus->rbuffer + size,
874 bus->rbuffer_size - size);
880 r = bus_message_from_malloc(bus,
882 bus->fds, bus->n_fds,
892 bus->rbuffer_size -= size;
897 bus->rqueue[bus->rqueue_size++] = t;
902 int bus_socket_read_message(sd_bus *bus) {
904 struct iovec iov = {};
910 struct cmsghdr cmsghdr;
911 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
913 struct cmsghdr *cmsg;
914 bool handle_cmsg = false;
917 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
919 r = bus_socket_read_message_need(bus, &need);
923 if (bus->rbuffer_size >= need)
924 return bus_socket_make_message(bus, need);
926 b = realloc(bus->rbuffer, need);
932 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
933 iov.iov_len = need - bus->rbuffer_size;
935 if (bus->prefer_readv)
936 k = readv(bus->input_fd, &iov, 1);
941 mh.msg_control = &control;
942 mh.msg_controllen = sizeof(control);
944 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
945 if (k < 0 && errno == ENOTSOCK) {
946 bus->prefer_readv = true;
947 k = readv(bus->input_fd, &iov, 1);
952 return errno == EAGAIN ? 0 : -errno;
956 bus->rbuffer_size += k;
959 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
960 if (cmsg->cmsg_level == SOL_SOCKET &&
961 cmsg->cmsg_type == SCM_RIGHTS) {
964 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
967 /* Whut? We received fds but this
968 * isn't actually enabled? Close them,
971 close_many((int*) CMSG_DATA(cmsg), n);
975 f = realloc(bus->fds, sizeof(int) + (bus->n_fds + n));
977 close_many((int*) CMSG_DATA(cmsg), n);
981 memcpy(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
985 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
986 cmsg->cmsg_level, cmsg->cmsg_type);
988 r = bus_socket_read_message_need(bus, &need);
992 if (bus->rbuffer_size >= need)
993 return bus_socket_make_message(bus, need);
998 int bus_socket_process_opening(sd_bus *b) {
1000 socklen_t slen = sizeof(error);
1007 assert(b->state == BUS_OPENING);
1013 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1016 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1018 b->last_connect_error = errno;
1019 else if (error != 0)
1020 b->last_connect_error = error;
1021 else if (p.revents & (POLLERR|POLLHUP))
1022 b->last_connect_error = ECONNREFUSED;
1024 return bus_socket_start_auth(b);
1026 return bus_next_address(b);
1029 int bus_socket_process_authenticating(sd_bus *b) {
1033 assert(b->state == BUS_AUTHENTICATING);
1035 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1038 r = bus_socket_write_auth(b);
1042 return bus_socket_read_auth(b);