blob: 3dbd11fd37272d81fb3d1b311ac8ad42c5817178 [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 Moreland19fc9f72021-06-10 03:57:30 +0000103 return addOutgoingConnection(std::move(serverFd));
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
221 int32_t id;
222
Steven Moreland195edb82021-06-08 02:44:39 +0000223 ExclusiveConnection connection;
224 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
225 ConnectionUse::CLIENT, &connection);
226 if (status != OK) return status;
227
Steven Moreland5ae62562021-06-10 03:21:42 +0000228 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &id);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000229 if (status != OK) return status;
230
231 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
232 mId = id;
233 return OK;
234}
235
Steven Moreland19fc9f72021-06-10 03:57:30 +0000236void RpcSession::WaitForShutdownListener::onSessionLockedAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000237 const sp<RpcSession>& session) {
238 (void)session;
239 mShutdown = true;
240}
241
Steven Moreland19fc9f72021-06-10 03:57:30 +0000242void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000243 mCv.notify_all();
244}
245
246void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
247 while (!mShutdown) {
248 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
249 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
250 }
251 }
252}
253
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000254void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000255 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256
Steven Morelanda63ff932021-05-12 00:03:15 +0000257 {
258 std::lock_guard<std::mutex> _l(mMutex);
259 mThreads[thread.get_id()] = std::move(thread);
260 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000261}
Steven Morelanda63ff932021-05-12 00:03:15 +0000262
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000263RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000264 // must be registered to allow arbitrary client code executing commands to
265 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000266 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267
Steven Moreland5ae62562021-06-10 03:21:42 +0000268 status_t status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000269
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000270 return PreJoinSetupResult{
271 .connection = std::move(connection),
272 .status = status,
273 };
274}
275
276void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
277 sp<RpcConnection>& connection = setupResult.connection;
278
279 if (setupResult.status == OK) {
280 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000281 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000282 RpcState::CommandType::ANY);
283 if (status != OK) {
284 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
285 statusToString(status).c_str());
286 break;
287 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000288 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000289 } else {
290 ALOGE("Connection failed to init, closing with status %s",
291 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292 }
293
Steven Moreland19fc9f72021-06-10 03:57:30 +0000294 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000296
Steven Moreland659416d2021-05-11 00:47:50 +0000297 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000298 {
Steven Moreland659416d2021-05-11 00:47:50 +0000299 std::lock_guard<std::mutex> _l(session->mMutex);
300 auto it = session->mThreads.find(std::this_thread::get_id());
301 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000302 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000303 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000304
Steven Moreland659416d2021-05-11 00:47:50 +0000305 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000306 }
307
Steven Moreland659416d2021-05-11 00:47:50 +0000308 session = nullptr;
309
310 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000311 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000312 }
313}
314
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315wp<RpcServer> RpcSession::server() {
316 return mForServer;
317}
318
319bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
320 {
321 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000322 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000323 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000324 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000325 }
326
Steven Moreland659416d2021-05-11 00:47:50 +0000327 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000328
Steven Morelanda5036f02021-06-08 02:26:57 +0000329 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000330 // instead of all at once.
331 // TODO(b/186470974): first risk of blocking
332 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000333 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000334 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
335 statusToString(status).c_str());
336 return false;
337 }
338
339 if (status_t status = readId(); status != OK) {
340 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
341 statusToString(status).c_str());
342 return false;
343 }
344
345 // we've already setup one client
346 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000347 // TODO(b/189955605): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000348 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
349 }
350
Steven Morelanda5036f02021-06-08 02:26:57 +0000351 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000352 // instead of all at once - the other side should be responsible for setting
353 // up additional connections. We need to create at least one (unless 0 are
354 // requested to be set) in order to allow the other side to reliably make
355 // any requests at all.
356
Steven Moreland103424e2021-06-02 18:16:19 +0000357 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000358 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000359 }
360
361 return true;
362}
363
Steven Moreland659416d2021-05-11 00:47:50 +0000364bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000365 for (size_t tries = 0; tries < 5; tries++) {
366 if (tries > 0) usleep(10000);
367
368 unique_fd serverFd(
369 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
370 if (serverFd == -1) {
371 int savedErrno = errno;
372 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
373 strerror(savedErrno));
374 return false;
375 }
376
377 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
378 if (errno == ECONNRESET) {
379 ALOGW("Connection reset on %s", addr.toString().c_str());
380 continue;
381 }
382 int savedErrno = errno;
383 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
384 strerror(savedErrno));
385 return false;
386 }
387
Steven Moreland659416d2021-05-11 00:47:50 +0000388 RpcConnectionHeader header{
389 .sessionId = id,
390 };
391 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
392
393 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000394 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000395 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000396 strerror(savedErrno));
397 return false;
398 }
399
400 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
401
Steven Moreland659416d2021-05-11 00:47:50 +0000402 if (reverse) {
403 std::mutex mutex;
404 std::condition_variable joinCv;
405 std::unique_lock<std::mutex> lock(mutex);
406 std::thread thread;
407 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
408 bool ownershipTransferred = false;
409 thread = std::thread([&]() {
410 std::unique_lock<std::mutex> threadLock(mutex);
411 unique_fd fd = std::move(serverFd);
412 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
413 sp<RpcSession> session = thiz;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000414 session->preJoinThreadOwnership(std::move(thread));
Steven Moreland659416d2021-05-11 00:47:50 +0000415
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000416 // only continue once we have a response or the connection fails
417 auto setupResult = session->preJoinSetup(std::move(fd));
418
419 ownershipTransferred = true;
Steven Moreland659416d2021-05-11 00:47:50 +0000420 threadLock.unlock();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000421 joinCv.notify_one();
Steven Moreland659416d2021-05-11 00:47:50 +0000422 // do not use & vars below
423
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000424 RpcSession::join(std::move(session), std::move(setupResult));
Steven Moreland659416d2021-05-11 00:47:50 +0000425 });
426 joinCv.wait(lock, [&] { return ownershipTransferred; });
427 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
428 return true;
429 } else {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000430 return addOutgoingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000431 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432 }
433
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000434 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
435 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436}
437
Steven Moreland19fc9f72021-06-10 03:57:30 +0000438bool RpcSession::addOutgoingConnection(unique_fd fd) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000439 sp<RpcConnection> connection = sp<RpcConnection>::make();
440 {
441 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000442
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000443 // first client connection added, but setForServer not called, so
444 // initializaing for a client.
445 if (mShutdownTrigger == nullptr) {
446 mShutdownTrigger = FdTrigger::make();
447 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
448 if (mShutdownTrigger == nullptr) return false;
449 }
450
451 connection->fd = std::move(fd);
452 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000453 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000454 }
455
Steven Moreland5ae62562021-06-10 03:21:42 +0000456 status_t status = mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000457
458 {
459 std::lock_guard<std::mutex> _l(mMutex);
460 connection->exclusiveTid = std::nullopt;
461 }
462
463 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464}
465
Steven Morelanda8b44292021-06-08 01:27:53 +0000466bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
467 int32_t sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000468 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
469 LOG_ALWAYS_FATAL_IF(server == nullptr);
470 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
471 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000472 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000473
474 mShutdownTrigger = FdTrigger::make();
475 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000476
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477 mId = sessionId;
478 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000479 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000480 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481}
482
Steven Moreland19fc9f72021-06-10 03:57:30 +0000483sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484 std::lock_guard<std::mutex> _l(mMutex);
485 sp<RpcConnection> session = sp<RpcConnection>::make();
486 session->fd = std::move(fd);
487 session->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000488 mIncomingConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489
490 return session;
491}
492
Steven Moreland19fc9f72021-06-10 03:57:30 +0000493bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000495 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
496 it != mIncomingConnections.end()) {
497 mIncomingConnections.erase(it);
498 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000499 sp<EventListener> listener = mEventListener.promote();
500 if (listener) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000501 listener->onSessionLockedAllIncomingThreadsEnded(
502 sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000503 }
Steven Morelandee78e762021-05-05 21:12:51 +0000504 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000505 return true;
506 }
507 return false;
508}
509
Steven Moreland195edb82021-06-08 02:44:39 +0000510status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
511 ExclusiveConnection* connection) {
512 connection->mSession = session;
513 connection->mConnection = nullptr;
514 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000515
Steven Moreland195edb82021-06-08 02:44:39 +0000516 pid_t tid = gettid();
517 std::unique_lock<std::mutex> _l(session->mMutex);
518
519 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000520 while (true) {
521 sp<RpcConnection> exclusive;
522 sp<RpcConnection> available;
523
524 // CHECK FOR DEDICATED CLIENT SOCKET
525 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000526 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000527 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
528 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529
530 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000531 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000532 //
533 // Imagine we have more than one thread in play, and a single thread
534 // sends a synchronous, then an asynchronous command. Imagine the
535 // asynchronous command is sent on the first client connection. Then, if
536 // we naively send a synchronous command to that same connection, the
537 // thread on the far side might be busy processing the asynchronous
538 // command. So, we move to considering the second available thread
539 // for subsequent calls.
540 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000541 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
542 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 }
544
Steven Morelandc7d40132021-06-10 03:42:11 +0000545 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000547 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000548 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000549 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
550 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000551
552 // asynchronous calls cannot be nested, we currently allow ref count
553 // calls to be nested (so that you can use this without having extra
554 // threads). Note 'drainCommands' is used so that these ref counts can't
555 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000556 if (exclusiveIncoming != nullptr) {
557 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000558 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000559 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000560 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
561 // prefer available socket, but if we don't have one, don't
562 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000563 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000564 }
565 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000566 }
567
Steven Moreland85e067b2021-05-26 17:43:53 +0000568 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000569 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000570 connection->mConnection = exclusive;
571 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000572 break;
573 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000574 connection->mConnection = available;
575 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000576 break;
577 }
578
Steven Moreland19fc9f72021-06-10 03:57:30 +0000579 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000580 ALOGE("Session has no client connections. This is required for an RPC server to make "
581 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
582 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000583 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000584 return WOULD_BLOCK;
585 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000586
Steven Moreland85e067b2021-05-26 17:43:53 +0000587 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000588 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000589 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000590 }
Steven Moreland195edb82021-06-08 02:44:39 +0000591 session->mWaitingThreads--;
592
593 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000594}
595
596void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
597 sp<RpcConnection>* available,
598 std::vector<sp<RpcConnection>>& sockets,
599 size_t socketsIndexHint) {
600 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
601 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
602
603 if (*exclusive != nullptr) return; // consistent with break below
604
605 for (size_t i = 0; i < sockets.size(); i++) {
606 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
607
Steven Moreland85e067b2021-05-26 17:43:53 +0000608 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000609 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
610 *available = socket;
611 continue;
612 }
613
Steven Moreland85e067b2021-05-26 17:43:53 +0000614 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000615 // (nested transactions)
616 if (exclusive && socket->exclusiveTid == tid) {
617 *exclusive = socket;
618 break; // consistent with return above
619 }
620 }
621}
622
623RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000624 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000625 // is using this fd, and it retains the right to it. So, we don't give up
626 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000627 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000628 std::unique_lock<std::mutex> _l(mSession->mMutex);
629 mConnection->exclusiveTid = std::nullopt;
630 if (mSession->mWaitingThreads > 0) {
631 _l.unlock();
632 mSession->mAvailableConnectionCv.notify_one();
633 }
634 }
635}
636
637} // namespace android