blob: ce60e33ba7f0c187630760562ce96889e66872c6 [file] [log] [blame]
Andrei Homescu7c0b79f2022-06-30 02:00:46 +00001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "OS.h"
18
19#include <android-base/file.h>
Andrei Homescu024727b2022-08-24 23:54:59 +000020#include <binder/RpcTransportRaw.h>
David Brazdil21c887c2022-09-23 12:25:18 +010021#include <log/log.h>
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000022#include <string.h>
23
24using android::base::ErrnoError;
25using android::base::Result;
26
27namespace android {
28
David Brazdil21c887c2022-09-23 12:25:18 +010029// Linux kernel supports up to 253 (from SCM_MAX_FD) for unix sockets.
30constexpr size_t kMaxFdsPerMsg = 253;
31
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000032Result<void> setNonBlocking(android::base::borrowed_fd fd) {
33 int flags = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_GETFL));
34 if (flags == -1) {
35 return ErrnoError() << "Could not get flags for fd";
36 }
37 if (int ret = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK)); ret == -1) {
38 return ErrnoError() << "Could not set non-blocking flag for fd";
39 }
40 return {};
41}
42
43status_t getRandomBytes(uint8_t* data, size_t size) {
44 int ret = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
45 if (ret == -1) {
46 return -errno;
47 }
48
49 base::unique_fd fd(ret);
50 if (!base::ReadFully(fd, data, size)) {
51 return -errno;
52 }
53 return OK;
54}
55
Andrei Homescu24ad36e2022-08-04 01:33:33 +000056status_t dupFileDescriptor(int oldFd, int* newFd) {
57 int ret = fcntl(oldFd, F_DUPFD_CLOEXEC, 0);
58 if (ret < 0) {
59 return -errno;
60 }
61
62 *newFd = ret;
63 return OK;
64}
65
Andrei Homescu024727b2022-08-24 23:54:59 +000066std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory() {
67 return RpcTransportCtxFactoryRaw::make();
68}
69
David Brazdilc3964f62022-10-24 23:06:14 +010070ssize_t sendMessageOnSocket(
David Brazdil21c887c2022-09-23 12:25:18 +010071 const RpcTransportFd& socket, iovec* iovs, int niovs,
72 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
73 if (ancillaryFds != nullptr && !ancillaryFds->empty()) {
74 if (ancillaryFds->size() > kMaxFdsPerMsg) {
75 errno = EINVAL;
76 return -1;
77 }
78
79 // CMSG_DATA is not necessarily aligned, so we copy the FDs into a buffer and then
80 // use memcpy.
81 int fds[kMaxFdsPerMsg];
82 for (size_t i = 0; i < ancillaryFds->size(); i++) {
83 fds[i] = std::visit([](const auto& fd) { return fd.get(); }, ancillaryFds->at(i));
84 }
85 const size_t fdsByteSize = sizeof(int) * ancillaryFds->size();
86
87 alignas(struct cmsghdr) char msgControlBuf[CMSG_SPACE(sizeof(int) * kMaxFdsPerMsg)];
88
89 msghdr msg{
90 .msg_iov = iovs,
91 .msg_iovlen = static_cast<decltype(msg.msg_iovlen)>(niovs),
92 .msg_control = msgControlBuf,
93 .msg_controllen = sizeof(msgControlBuf),
94 };
95
96 cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
97 cmsg->cmsg_level = SOL_SOCKET;
98 cmsg->cmsg_type = SCM_RIGHTS;
99 cmsg->cmsg_len = CMSG_LEN(fdsByteSize);
100 memcpy(CMSG_DATA(cmsg), fds, fdsByteSize);
101
102 msg.msg_controllen = CMSG_SPACE(fdsByteSize);
103 return TEMP_FAILURE_RETRY(sendmsg(socket.fd.get(), &msg, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC));
104 }
105
106 msghdr msg{
107 .msg_iov = iovs,
108 // posix uses int, glibc uses size_t. niovs is a
109 // non-negative int and can be cast to either.
110 .msg_iovlen = static_cast<decltype(msg.msg_iovlen)>(niovs),
111 };
112 return TEMP_FAILURE_RETRY(sendmsg(socket.fd.get(), &msg, MSG_NOSIGNAL));
113}
114
David Brazdilc3964f62022-10-24 23:06:14 +0100115ssize_t receiveMessageFromSocket(
David Brazdil21c887c2022-09-23 12:25:18 +0100116 const RpcTransportFd& socket, iovec* iovs, int niovs,
117 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
118 if (ancillaryFds != nullptr) {
119 int fdBuffer[kMaxFdsPerMsg];
120 alignas(struct cmsghdr) char msgControlBuf[CMSG_SPACE(sizeof(fdBuffer))];
121
122 msghdr msg{
123 .msg_iov = iovs,
124 .msg_iovlen = static_cast<decltype(msg.msg_iovlen)>(niovs),
125 .msg_control = msgControlBuf,
126 .msg_controllen = sizeof(msgControlBuf),
127 };
128 ssize_t processSize = TEMP_FAILURE_RETRY(recvmsg(socket.fd.get(), &msg, MSG_NOSIGNAL));
129 if (processSize < 0) {
130 return -1;
131 }
132
133 for (cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
134 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
135 // NOTE: It is tempting to reinterpret_cast, but cmsg(3) explicitly asks
136 // application devs to memcpy the data to ensure memory alignment.
137 size_t dataLen = cmsg->cmsg_len - CMSG_LEN(0);
138 LOG_ALWAYS_FATAL_IF(dataLen > sizeof(fdBuffer)); // validity check
139 memcpy(fdBuffer, CMSG_DATA(cmsg), dataLen);
140 size_t fdCount = dataLen / sizeof(int);
141 ancillaryFds->reserve(ancillaryFds->size() + fdCount);
142 for (size_t i = 0; i < fdCount; i++) {
143 ancillaryFds->emplace_back(base::unique_fd(fdBuffer[i]));
144 }
145 break;
146 }
147 }
148
149 if (msg.msg_flags & MSG_CTRUNC) {
150 errno = EPIPE;
151 return -1;
152 }
153 return processSize;
154 }
155 msghdr msg{
156 .msg_iov = iovs,
157 // posix uses int, glibc uses size_t. niovs is a
158 // non-negative int and can be cast to either.
159 .msg_iovlen = static_cast<decltype(msg.msg_iovlen)>(niovs),
160 };
161
162 return TEMP_FAILURE_RETRY(recvmsg(socket.fd.get(), &msg, MSG_NOSIGNAL));
163}
164
Andrei Homescu7c0b79f2022-06-30 02:00:46 +0000165} // namespace android