blob: 4f55eef2d1097c2d8642050b9c85120660ef0d7a [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +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 "RpcSession"
18
19#include <binder/RpcSession.h>
20
21#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000022#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000023#include <unistd.h>
24
25#include <string_view>
26
Steven Moreland4ec3c432021-05-20 00:32:47 +000027#include <android-base/macros.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000028#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000029#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000030#include <binder/Stability.h>
31#include <utils/String8.h>
32
33#include "RpcSocketAddress.h"
34#include "RpcState.h"
35#include "RpcWireFormat.h"
36
37#ifdef __GLIBC__
38extern "C" pid_t gettid();
39#endif
40
41namespace android {
42
43using base::unique_fd;
44
45RpcSession::RpcSession() {
46 LOG_RPC_DETAIL("RpcSession created %p", this);
47
48 mState = std::make_unique<RpcState>();
49}
50RpcSession::~RpcSession() {
51 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
52
53 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000054 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055 "Should not be able to destroy a session with servers in use.");
56}
57
58sp<RpcSession> RpcSession::make() {
59 return sp<RpcSession>::make();
60}
61
Steven Moreland103424e2021-06-02 18:16:19 +000062void RpcSession::setMaxThreads(size_t threads) {
63 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000064 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000065 "Must set max threads before setting up connections, but has %zu client(s) "
66 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000067 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000068 mMaxThreads = threads;
69}
70
71size_t RpcSession::getMaxThreads() {
72 std::lock_guard<std::mutex> _l(mMutex);
73 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000074}
75
Steven Morelandbdb53ab2021-05-05 17:57:41 +000076bool RpcSession::setupUnixDomainClient(const char* path) {
77 return setupSocketClient(UnixSocketAddress(path));
78}
79
Steven Morelandbdb53ab2021-05-05 17:57:41 +000080bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
81 return setupSocketClient(VsockSocketAddress(cid, port));
82}
83
Steven Morelandbdb53ab2021-05-05 17:57:41 +000084bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
85 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
86 if (aiStart == nullptr) return false;
87 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
88 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
89 if (setupSocketClient(socketAddress)) return true;
90 }
91 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
92 return false;
93}
94
95bool RpcSession::addNullDebuggingClient() {
96 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
97
98 if (serverFd == -1) {
99 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
100 return false;
101 }
102
Steven Morelandb86e26b2021-06-12 00:35:58 +0000103 return addOutgoingConnection(std::move(serverFd), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000104}
105
106sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000107 ExclusiveConnection connection;
108 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
109 ConnectionUse::CLIENT, &connection);
110 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000111 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000112}
113
Steven Moreland1be91352021-05-11 22:12:15 +0000114status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000115 ExclusiveConnection connection;
116 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
117 ConnectionUse::CLIENT, &connection);
118 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000119 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000120}
121
Steven Morelandc9d7b532021-06-04 20:57:41 +0000122bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000123 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000124 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000125
126 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000127
Steven Morelandc9d7b532021-06-04 20:57:41 +0000128 if (wait) {
129 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
130 mShutdownListener->waitForShutdown(_l);
131 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
132 }
133
134 _l.unlock();
135 mState->clear();
136
Steven Moreland659416d2021-05-11 00:47:50 +0000137 return true;
138}
139
Steven Morelandf5174272021-05-25 00:39:28 +0000140status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000142 ExclusiveConnection connection;
143 status_t status =
144 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
145 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
146 : ConnectionUse::CLIENT,
147 &connection);
148 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000149 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000150 sp<RpcSession>::fromExisting(this), reply, flags);
151}
152
153status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000154 ExclusiveConnection connection;
155 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
156 ConnectionUse::CLIENT_REFCOUNT, &connection);
157 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000158 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159}
160
Steven Morelande47511f2021-05-20 00:07:41 +0000161std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
162 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000163 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
164 ALOGE("Could not create pipe %s", strerror(errno));
165 return nullptr;
166 }
Steven Morelande47511f2021-05-20 00:07:41 +0000167 return ret;
168}
169
170void RpcSession::FdTrigger::trigger() {
171 mWrite.reset();
172}
173
Steven Morelanda8b44292021-06-08 01:27:53 +0000174bool RpcSession::FdTrigger::isTriggered() {
175 return mWrite == -1;
176}
177
Steven Moreland2b4f3802021-05-22 01:46:27 +0000178status_t RpcSession::FdTrigger::triggerablePollRead(base::borrowed_fd fd) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000179 while (true) {
Steven Morelanddfe3be92021-05-22 00:24:29 +0000180 pollfd pfd[]{{.fd = fd.get(), .events = POLLIN | POLLHUP, .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000181 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
182 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
183 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000184 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000185 }
186 if (ret == 0) {
187 continue;
188 }
189 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000190 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000191 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000192 return pfd[0].revents & POLLIN ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000193 }
194}
195
Steven Moreland2b4f3802021-05-22 01:46:27 +0000196status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
197 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000198 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
199 uint8_t* end = buffer + size;
200
Steven Moreland2b4f3802021-05-22 01:46:27 +0000201 status_t status;
202 while ((status = triggerablePollRead(fd)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000203 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000204 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000205
Steven Moreland9d11b922021-05-20 01:22:58 +0000206 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000207 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000208 }
209 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000210 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000211 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000212 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000213}
214
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215status_t RpcSession::readId() {
216 {
217 std::lock_guard<std::mutex> _l(mMutex);
218 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
219 }
220
Steven Moreland195edb82021-06-08 02:44:39 +0000221 ExclusiveConnection connection;
222 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
223 ConnectionUse::CLIENT, &connection);
224 if (status != OK) return status;
225
Steven Moreland01a6bad2021-06-11 00:59:20 +0000226 mId = RpcAddress::zero();
227 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
228 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000229 if (status != OK) return status;
230
Steven Moreland01a6bad2021-06-11 00:59:20 +0000231 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000232 return OK;
233}
234
Steven Moreland19fc9f72021-06-10 03:57:30 +0000235void RpcSession::WaitForShutdownListener::onSessionLockedAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000236 const sp<RpcSession>& session) {
237 (void)session;
238 mShutdown = true;
239}
240
Steven Moreland19fc9f72021-06-10 03:57:30 +0000241void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000242 mCv.notify_all();
243}
244
245void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
246 while (!mShutdown) {
247 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
248 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
249 }
250 }
251}
252
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000253void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000254 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255
Steven Morelanda63ff932021-05-12 00:03:15 +0000256 {
257 std::lock_guard<std::mutex> _l(mMutex);
258 mThreads[thread.get_id()] = std::move(thread);
259 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000260}
Steven Morelanda63ff932021-05-12 00:03:15 +0000261
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000262RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000263 // must be registered to allow arbitrary client code executing commands to
264 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000265 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000266
Steven Moreland5ae62562021-06-10 03:21:42 +0000267 status_t status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000268
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000269 return PreJoinSetupResult{
270 .connection = std::move(connection),
271 .status = status,
272 };
273}
274
275void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
276 sp<RpcConnection>& connection = setupResult.connection;
277
278 if (setupResult.status == OK) {
279 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000280 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000281 RpcState::CommandType::ANY);
282 if (status != OK) {
283 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
284 statusToString(status).c_str());
285 break;
286 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000288 } else {
289 ALOGE("Connection failed to init, closing with status %s",
290 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 }
292
Steven Moreland19fc9f72021-06-10 03:57:30 +0000293 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000295
Steven Moreland659416d2021-05-11 00:47:50 +0000296 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000297 {
Steven Moreland659416d2021-05-11 00:47:50 +0000298 std::lock_guard<std::mutex> _l(session->mMutex);
299 auto it = session->mThreads.find(std::this_thread::get_id());
300 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000301 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000302 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000303
Steven Moreland659416d2021-05-11 00:47:50 +0000304 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000305 }
306
Steven Moreland659416d2021-05-11 00:47:50 +0000307 session = nullptr;
308
309 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000310 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000311 }
312}
313
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000314sp<RpcServer> RpcSession::server() {
315 RpcServer* unsafeServer = mForServer.unsafe_get();
316 sp<RpcServer> server = mForServer.promote();
317
318 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
319 "wp<> is to avoid strong cycle only");
320 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000321}
322
323bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
324 {
325 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000326 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000327 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000328 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329 }
330
Steven Moreland01a6bad2021-06-11 00:59:20 +0000331 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332
Steven Morelanda5036f02021-06-08 02:26:57 +0000333 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000334 // instead of all at once.
335 // TODO(b/186470974): first risk of blocking
336 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000337 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000338 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
339 statusToString(status).c_str());
340 return false;
341 }
342
343 if (status_t status = readId(); status != OK) {
344 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
345 statusToString(status).c_str());
346 return false;
347 }
348
349 // we've already setup one client
350 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000351 // TODO(b/189955605): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000352 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
353 }
354
Steven Morelanda5036f02021-06-08 02:26:57 +0000355 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000356 // instead of all at once - the other side should be responsible for setting
357 // up additional connections. We need to create at least one (unless 0 are
358 // requested to be set) in order to allow the other side to reliably make
359 // any requests at all.
360
Steven Moreland103424e2021-06-02 18:16:19 +0000361 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000362 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000363 }
364
365 return true;
366}
367
Steven Moreland01a6bad2021-06-11 00:59:20 +0000368bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
369 bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000370 for (size_t tries = 0; tries < 5; tries++) {
371 if (tries > 0) usleep(10000);
372
373 unique_fd serverFd(
374 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
375 if (serverFd == -1) {
376 int savedErrno = errno;
377 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
378 strerror(savedErrno));
379 return false;
380 }
381
382 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
383 if (errno == ECONNRESET) {
384 ALOGW("Connection reset on %s", addr.toString().c_str());
385 continue;
386 }
387 int savedErrno = errno;
388 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
389 strerror(savedErrno));
390 return false;
391 }
392
Steven Moreland01a6bad2021-06-11 00:59:20 +0000393 RpcConnectionHeader header{.options = 0};
394 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
395
Steven Moreland659416d2021-05-11 00:47:50 +0000396 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
397
398 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000399 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000400 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000401 strerror(savedErrno));
402 return false;
403 }
404
405 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
406
Steven Moreland659416d2021-05-11 00:47:50 +0000407 if (reverse) {
408 std::mutex mutex;
409 std::condition_variable joinCv;
410 std::unique_lock<std::mutex> lock(mutex);
411 std::thread thread;
412 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
413 bool ownershipTransferred = false;
414 thread = std::thread([&]() {
415 std::unique_lock<std::mutex> threadLock(mutex);
416 unique_fd fd = std::move(serverFd);
417 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
418 sp<RpcSession> session = thiz;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000419 session->preJoinThreadOwnership(std::move(thread));
Steven Moreland659416d2021-05-11 00:47:50 +0000420
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000421 // only continue once we have a response or the connection fails
422 auto setupResult = session->preJoinSetup(std::move(fd));
423
424 ownershipTransferred = true;
Steven Moreland659416d2021-05-11 00:47:50 +0000425 threadLock.unlock();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000426 joinCv.notify_one();
Steven Moreland659416d2021-05-11 00:47:50 +0000427 // do not use & vars below
428
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000429 RpcSession::join(std::move(session), std::move(setupResult));
Steven Moreland659416d2021-05-11 00:47:50 +0000430 });
431 joinCv.wait(lock, [&] { return ownershipTransferred; });
432 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
433 return true;
434 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000435 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000436 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437 }
438
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000439 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
440 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441}
442
Steven Morelandb86e26b2021-06-12 00:35:58 +0000443bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000444 sp<RpcConnection> connection = sp<RpcConnection>::make();
445 {
446 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000447
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000448 // first client connection added, but setForServer not called, so
449 // initializaing for a client.
450 if (mShutdownTrigger == nullptr) {
451 mShutdownTrigger = FdTrigger::make();
452 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
453 if (mShutdownTrigger == nullptr) return false;
454 }
455
456 connection->fd = std::move(fd);
457 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000458 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000459 }
460
Steven Morelandb86e26b2021-06-12 00:35:58 +0000461 status_t status = OK;
462 if (init) {
463 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
464 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000465
466 {
467 std::lock_guard<std::mutex> _l(mMutex);
468 connection->exclusiveTid = std::nullopt;
469 }
470
471 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472}
473
Steven Morelanda8b44292021-06-08 01:27:53 +0000474bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000475 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000476 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
477 LOG_ALWAYS_FATAL_IF(server == nullptr);
478 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
479 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000480 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000481
482 mShutdownTrigger = FdTrigger::make();
483 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000484
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485 mId = sessionId;
486 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000487 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000488 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489}
490
Steven Moreland19fc9f72021-06-10 03:57:30 +0000491sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000492 std::lock_guard<std::mutex> _l(mMutex);
493 sp<RpcConnection> session = sp<RpcConnection>::make();
494 session->fd = std::move(fd);
495 session->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000496 mIncomingConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000497
498 return session;
499}
500
Steven Moreland19fc9f72021-06-10 03:57:30 +0000501bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000502 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000503 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
504 it != mIncomingConnections.end()) {
505 mIncomingConnections.erase(it);
506 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000507 sp<EventListener> listener = mEventListener.promote();
508 if (listener) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000509 listener->onSessionLockedAllIncomingThreadsEnded(
510 sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000511 }
Steven Morelandee78e762021-05-05 21:12:51 +0000512 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000513 return true;
514 }
515 return false;
516}
517
Steven Moreland195edb82021-06-08 02:44:39 +0000518status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
519 ExclusiveConnection* connection) {
520 connection->mSession = session;
521 connection->mConnection = nullptr;
522 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000523
Steven Moreland195edb82021-06-08 02:44:39 +0000524 pid_t tid = gettid();
525 std::unique_lock<std::mutex> _l(session->mMutex);
526
527 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000528 while (true) {
529 sp<RpcConnection> exclusive;
530 sp<RpcConnection> available;
531
532 // CHECK FOR DEDICATED CLIENT SOCKET
533 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000534 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000535 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
536 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000537
538 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000539 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 //
541 // Imagine we have more than one thread in play, and a single thread
542 // sends a synchronous, then an asynchronous command. Imagine the
543 // asynchronous command is sent on the first client connection. Then, if
544 // we naively send a synchronous command to that same connection, the
545 // thread on the far side might be busy processing the asynchronous
546 // command. So, we move to considering the second available thread
547 // for subsequent calls.
548 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000549 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
550 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000551 }
552
Steven Morelandc7d40132021-06-10 03:42:11 +0000553 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000554 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000555 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000556 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000557 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
558 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000559
560 // asynchronous calls cannot be nested, we currently allow ref count
561 // calls to be nested (so that you can use this without having extra
562 // threads). Note 'drainCommands' is used so that these ref counts can't
563 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000564 if (exclusiveIncoming != nullptr) {
565 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000566 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000567 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000568 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
569 // prefer available socket, but if we don't have one, don't
570 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000571 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000572 }
573 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000574 }
575
Steven Moreland85e067b2021-05-26 17:43:53 +0000576 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000577 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000578 connection->mConnection = exclusive;
579 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000580 break;
581 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000582 connection->mConnection = available;
583 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000584 break;
585 }
586
Steven Moreland19fc9f72021-06-10 03:57:30 +0000587 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000588 ALOGE("Session has no client connections. This is required for an RPC server to make "
589 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
590 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000591 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000592 return WOULD_BLOCK;
593 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000594
Steven Moreland85e067b2021-05-26 17:43:53 +0000595 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000596 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000597 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000598 }
Steven Moreland195edb82021-06-08 02:44:39 +0000599 session->mWaitingThreads--;
600
601 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000602}
603
604void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
605 sp<RpcConnection>* available,
606 std::vector<sp<RpcConnection>>& sockets,
607 size_t socketsIndexHint) {
608 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
609 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
610
611 if (*exclusive != nullptr) return; // consistent with break below
612
613 for (size_t i = 0; i < sockets.size(); i++) {
614 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
615
Steven Moreland85e067b2021-05-26 17:43:53 +0000616 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000617 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
618 *available = socket;
619 continue;
620 }
621
Steven Moreland85e067b2021-05-26 17:43:53 +0000622 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000623 // (nested transactions)
624 if (exclusive && socket->exclusiveTid == tid) {
625 *exclusive = socket;
626 break; // consistent with return above
627 }
628 }
629}
630
631RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000632 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000633 // is using this fd, and it retains the right to it. So, we don't give up
634 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000635 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000636 std::unique_lock<std::mutex> _l(mSession->mMutex);
637 mConnection->exclusiveTid = std::nullopt;
638 if (mSession->mWaitingThreads > 0) {
639 _l.unlock();
640 mSession->mAvailableConnectionCv.notify_one();
641 }
642 }
643}
644
645} // namespace android