blob: 376b0b623f99aceb3528c9bbacb2aab21ec21d3a [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 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#define LOG_TAG "RpcConnection"
18
19#include <binder/RpcConnection.h>
20
21#include <binder/Parcel.h>
22#include <binder/Stability.h>
Steven Morelandc1635952021-04-01 16:20:47 +000023#include <utils/String8.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024
25#include "RpcState.h"
26#include "RpcWireFormat.h"
27
28#include <sys/socket.h>
29#include <sys/types.h>
30#include <sys/un.h>
31#include <unistd.h>
32
Steven Morelandc1635952021-04-01 16:20:47 +000033#ifdef __GLIBC__
Steven Moreland5553ac42020-11-11 02:14:45 +000034extern "C" pid_t gettid();
35#endif
36
Steven Morelandc1635952021-04-01 16:20:47 +000037#ifdef __BIONIC__
38#include <linux/vm_sockets.h>
39#endif
40
Steven Moreland5553ac42020-11-11 02:14:45 +000041namespace android {
42
43using base::unique_fd;
44
Steven Morelandc1635952021-04-01 16:20:47 +000045RpcConnection::SocketAddress::~SocketAddress() {}
46
Steven Moreland5553ac42020-11-11 02:14:45 +000047RpcConnection::RpcConnection() {
48 LOG_RPC_DETAIL("RpcConnection created %p", this);
49
50 mState = std::make_unique<RpcState>();
51}
52RpcConnection::~RpcConnection() {
53 LOG_RPC_DETAIL("RpcConnection destroyed %p", this);
54}
55
56sp<RpcConnection> RpcConnection::make() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +000057 return sp<RpcConnection>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +000058}
59
Steven Morelandc1635952021-04-01 16:20:47 +000060class UnixSocketAddress : public RpcConnection::SocketAddress {
61public:
62 explicit UnixSocketAddress(const char* path) : mAddr({.sun_family = AF_UNIX}) {
63 unsigned int pathLen = strlen(path) + 1;
64 LOG_ALWAYS_FATAL_IF(pathLen > sizeof(mAddr.sun_path), "%u %s", pathLen, path);
65 memcpy(mAddr.sun_path, path, pathLen);
66 }
67 virtual ~UnixSocketAddress() {}
68 std::string toString() const override {
69 return String8::format("path '%.*s'", static_cast<int>(sizeof(mAddr.sun_path)),
70 mAddr.sun_path)
71 .c_str();
72 }
73 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
74 size_t addrSize() const override { return sizeof(mAddr); }
75
76private:
77 sockaddr_un mAddr;
78};
79
Steven Moreland5553ac42020-11-11 02:14:45 +000080bool RpcConnection::setupUnixDomainServer(const char* path) {
Steven Morelandc1635952021-04-01 16:20:47 +000081 return addServer(UnixSocketAddress(path));
Steven Moreland5553ac42020-11-11 02:14:45 +000082}
83
84bool RpcConnection::addUnixDomainClient(const char* path) {
Steven Morelandc1635952021-04-01 16:20:47 +000085 return addClient(UnixSocketAddress(path));
Steven Moreland53583542021-03-30 00:25:41 +000086}
87
Steven Morelandc1635952021-04-01 16:20:47 +000088#ifdef __BIONIC__
89
90class VsockSocketAddress : public RpcConnection::SocketAddress {
91public:
92 VsockSocketAddress(unsigned int cid, unsigned int port)
93 : mAddr({
94 .svm_family = AF_VSOCK,
95 .svm_port = port,
96 .svm_cid = cid,
97 }) {}
98 virtual ~VsockSocketAddress() {}
99 std::string toString() const override {
Yifan Hong4c791532021-04-14 12:38:46 -0700100 return String8::format("cid %u port %u", mAddr.svm_cid, mAddr.svm_port).c_str();
Steven Morelandc1635952021-04-01 16:20:47 +0000101 }
102 const sockaddr* addr() const override { return reinterpret_cast<const sockaddr*>(&mAddr); }
103 size_t addrSize() const override { return sizeof(mAddr); }
104
105private:
106 sockaddr_vm mAddr;
107};
108
109bool RpcConnection::setupVsockServer(unsigned int port) {
110 // realizing value w/ this type at compile time to avoid ubsan abort
111 constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
112
113 return addServer(VsockSocketAddress(kAnyCid, port));
114}
115
116bool RpcConnection::addVsockClient(unsigned int cid, unsigned int port) {
117 return addClient(VsockSocketAddress(cid, port));
118}
119
120#endif // __BIONIC__
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122sp<IBinder> RpcConnection::getRootObject() {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000123 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT);
124 return state()->getRootObject(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000125}
126
127status_t RpcConnection::transact(const RpcAddress& address, uint32_t code, const Parcel& data,
128 Parcel* reply, uint32_t flags) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000129 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this),
Steven Moreland5553ac42020-11-11 02:14:45 +0000130 (flags & IBinder::FLAG_ONEWAY) ? SocketUse::CLIENT_ASYNC
131 : SocketUse::CLIENT);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000132 return state()->transact(socket.fd(), address, code, data,
133 sp<RpcConnection>::fromExisting(this), reply, flags);
Steven Moreland5553ac42020-11-11 02:14:45 +0000134}
135
136status_t RpcConnection::sendDecStrong(const RpcAddress& address) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000137 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::CLIENT_REFCOUNT);
Steven Moreland5553ac42020-11-11 02:14:45 +0000138 return state()->sendDecStrong(socket.fd(), address);
139}
140
141void RpcConnection::join() {
142 // establish a connection
143 {
Steven Morelandc1635952021-04-01 16:20:47 +0000144 unique_fd clientFd(
145 TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, 0 /*length*/, SOCK_CLOEXEC)));
Steven Moreland5553ac42020-11-11 02:14:45 +0000146 if (clientFd < 0) {
147 // If this log becomes confusing, should save more state from setupUnixDomainServer
148 // in order to output here.
149 ALOGE("Could not accept4 socket: %s", strerror(errno));
150 return;
151 }
152
153 LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
154
Steven Morelandc1635952021-04-01 16:20:47 +0000155 assignServerToThisThread(std::move(clientFd));
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 }
157
158 // We may not use the connection we just established (two threads might
159 // establish connections for each other), but for now, just use one
160 // server/socket connection.
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000161 ExclusiveSocket socket(sp<RpcConnection>::fromExisting(this), SocketUse::SERVER);
Steven Moreland5553ac42020-11-11 02:14:45 +0000162
163 while (true) {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000164 status_t error =
165 state()->getAndExecuteCommand(socket.fd(), sp<RpcConnection>::fromExisting(this));
Steven Moreland5553ac42020-11-11 02:14:45 +0000166
167 if (error != OK) {
168 ALOGI("Binder socket thread closing w/ status %s", statusToString(error).c_str());
169 return;
170 }
171 }
172}
173
174void RpcConnection::setForServer(const wp<RpcServer>& server) {
175 mForServer = server;
176}
177
178wp<RpcServer> RpcConnection::server() {
179 return mForServer;
180}
181
Steven Morelandc1635952021-04-01 16:20:47 +0000182bool RpcConnection::addServer(const SocketAddress& addr) {
183 LOG_ALWAYS_FATAL_IF(mServer.get() != -1, "Each RpcConnection can only have one server.");
184
185 unique_fd serverFd(
186 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
187 if (serverFd == -1) {
188 ALOGE("Could not create socket: %s", strerror(errno));
189 return false;
190 }
191
192 if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
193 int savedErrno = errno;
194 ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
195 return false;
196 }
197
198 if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/))) {
199 int savedErrno = errno;
200 ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
201 return false;
202 }
203
204 mServer = std::move(serverFd);
205 return true;
Steven Moreland53583542021-03-30 00:25:41 +0000206}
207
Steven Morelandc1635952021-04-01 16:20:47 +0000208bool RpcConnection::addClient(const SocketAddress& addr) {
209 unique_fd serverFd(
210 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
211 if (serverFd == -1) {
212 int savedErrno = errno;
213 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
214 return false;
215 }
216
217 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
218 int savedErrno = errno;
219 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
220 return false;
221 }
222
223 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
224
225 std::lock_guard<std::mutex> _l(mSocketMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000226 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
Steven Morelandc1635952021-04-01 16:20:47 +0000227 connection->fd = std::move(serverFd);
228 mClients.push_back(connection);
229 return true;
230}
231
232void RpcConnection::assignServerToThisThread(base::unique_fd&& fd) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000233 std::lock_guard<std::mutex> _l(mSocketMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000234 sp<ConnectionSocket> connection = sp<ConnectionSocket>::make();
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 connection->fd = std::move(fd);
236 mServers.push_back(connection);
237}
238
239RpcConnection::ExclusiveSocket::ExclusiveSocket(const sp<RpcConnection>& connection, SocketUse use)
240 : mConnection(connection) {
241 pid_t tid = gettid();
242 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
243
244 mConnection->mWaitingThreads++;
245 while (true) {
246 sp<ConnectionSocket> exclusive;
247 sp<ConnectionSocket> available;
248
249 // CHECK FOR DEDICATED CLIENT SOCKET
250 //
251 // A server/looper should always use a dedicated connection.
252 if (use != SocketUse::SERVER) {
253 findSocket(tid, &exclusive, &available, mConnection->mClients,
254 mConnection->mClientsOffset);
255
256 // WARNING: this assumes a server cannot request its client to send
257 // a transaction, as mServers is excluded below.
258 //
259 // Imagine we have more than one thread in play, and a single thread
260 // sends a synchronous, then an asynchronous command. Imagine the
261 // asynchronous command is sent on the first client socket. Then, if
262 // we naively send a synchronous command to that same socket, the
263 // thread on the far side might be busy processing the asynchronous
264 // command. So, we move to considering the second available thread
265 // for subsequent calls.
266 if (use == SocketUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
267 mConnection->mClientsOffset =
268 (mConnection->mClientsOffset + 1) % mConnection->mClients.size();
269 }
270 }
271
272 // USE SERVING SOCKET (to start serving or for nested transaction)
273 //
274 // asynchronous calls cannot be nested
275 if (use != SocketUse::CLIENT_ASYNC) {
276 // servers should start serving on an available thread only
277 // otherwise, this should only be a nested call
278 bool useAvailable = use == SocketUse::SERVER;
279
280 findSocket(tid, &exclusive, (useAvailable ? &available : nullptr),
281 mConnection->mServers, 0 /* index hint */);
282 }
283
284 // if our thread is already using a connection, prioritize using that
285 if (exclusive != nullptr) {
286 mSocket = exclusive;
287 mReentrant = true;
288 break;
289 } else if (available != nullptr) {
290 mSocket = available;
291 mSocket->exclusiveTid = tid;
292 break;
293 }
294
295 LOG_ALWAYS_FATAL_IF(use == SocketUse::SERVER, "Must create connection to join one.");
296
297 // in regular binder, this would usually be a deadlock :)
298 LOG_ALWAYS_FATAL_IF(mConnection->mClients.size() == 0,
299 "Not a client of any connection. You must create a connection to an "
300 "RPC server to make any non-nested (e.g. oneway or on another thread) "
301 "calls.");
302
303 LOG_RPC_DETAIL("No available connection (have %zu clients and %zu servers). Waiting...",
304 mConnection->mClients.size(), mConnection->mServers.size());
305 mConnection->mSocketCv.wait(_l);
306 }
307 mConnection->mWaitingThreads--;
308}
309
310void RpcConnection::ExclusiveSocket::findSocket(pid_t tid, sp<ConnectionSocket>* exclusive,
311 sp<ConnectionSocket>* available,
312 std::vector<sp<ConnectionSocket>>& sockets,
313 size_t socketsIndexHint) {
314 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
315 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
316
317 if (*exclusive != nullptr) return; // consistent with break below
318
319 for (size_t i = 0; i < sockets.size(); i++) {
320 sp<ConnectionSocket>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
321
322 // take first available connection (intuition = caching)
323 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
324 *available = socket;
325 continue;
326 }
327
328 // though, prefer to take connection which is already inuse by this thread
329 // (nested transactions)
330 if (exclusive && socket->exclusiveTid == tid) {
331 *exclusive = socket;
332 break; // consistent with return above
333 }
334 }
335}
336
337RpcConnection::ExclusiveSocket::~ExclusiveSocket() {
338 // reentrant use of a connection means something less deep in the call stack
339 // is using this fd, and it retains the right to it. So, we don't give up
340 // exclusive ownership, and no thread is freed.
341 if (!mReentrant) {
342 std::unique_lock<std::mutex> _l(mConnection->mSocketMutex);
343 mSocket->exclusiveTid = std::nullopt;
344 if (mConnection->mWaitingThreads > 0) {
345 _l.unlock();
346 mConnection->mSocketCv.notify_one();
347 }
348 }
349}
350
351} // namespace android