blob: 886a2e952b6e32d398e87ffc230d3dc627304bcd [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
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000023#include <poll.h>
Yifan Hong194acf22021-06-29 18:44:56 -070024#include <pthread.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland826367f2021-09-10 14:05:31 -070029#include <android-base/hex.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000030#include <android-base/macros.h>
Yifan Hong194acf22021-06-29 18:44:56 -070031#include <android_runtime/vm.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070032#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000033#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000034#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070035#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000036#include <binder/Stability.h>
Yifan Hong194acf22021-06-29 18:44:56 -070037#include <jni.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000038#include <utils/String8.h>
39
Yifan Hong8c950422021-08-05 17:13:55 -070040#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000041#include "RpcSocketAddress.h"
42#include "RpcState.h"
43#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070044#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045
46#ifdef __GLIBC__
47extern "C" pid_t gettid();
48#endif
49
50namespace android {
51
52using base::unique_fd;
53
Yifan Hongecf937d2021-08-11 17:29:28 -070054RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055 LOG_RPC_DETAIL("RpcSession created %p", this);
56
57 mState = std::make_unique<RpcState>();
58}
59RpcSession::~RpcSession() {
60 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
61
62 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000063 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000064 "Should not be able to destroy a session with servers in use.");
65}
66
Yifan Hongecf937d2021-08-11 17:29:28 -070067sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070068 // Default is without TLS.
Yifan Hongecf937d2021-08-11 17:29:28 -070069 return make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
70}
71
72sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory,
73 std::optional<CertificateFormat> serverCertificateFormat,
74 std::optional<std::string> serverCertificate) {
75 auto ctx = rpcTransportCtxFactory->newClientCtx();
76 if (ctx == nullptr) return nullptr;
77 LOG_ALWAYS_FATAL_IF(serverCertificateFormat.has_value() != serverCertificate.has_value());
78 if (serverCertificateFormat.has_value() && serverCertificate.has_value()) {
79 status_t status =
80 ctx->addTrustedPeerCertificate(*serverCertificateFormat, *serverCertificate);
81 if (status != OK) {
82 ALOGE("Cannot add trusted server certificate: %s", statusToString(status).c_str());
83 return nullptr;
84 }
85 }
86 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000087}
88
Steven Moreland103424e2021-06-02 18:16:19 +000089void RpcSession::setMaxThreads(size_t threads) {
90 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000091 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000092 "Must set max threads before setting up connections, but has %zu client(s) "
93 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000094 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000095 mMaxThreads = threads;
96}
97
98size_t RpcSession::getMaxThreads() {
99 std::lock_guard<std::mutex> _l(mMutex);
100 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +0000101}
102
Steven Morelandbf57bce2021-07-26 15:26:12 -0700103bool RpcSession::setProtocolVersion(uint32_t version) {
104 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
105 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
106 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
107 "is %u).",
108 version, RPC_WIRE_PROTOCOL_VERSION);
109 return false;
110 }
111
112 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700113 if (mProtocolVersion && version > *mProtocolVersion) {
114 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
115 *mProtocolVersion, version);
116 return false;
117 }
118
Steven Morelandbf57bce2021-07-26 15:26:12 -0700119 mProtocolVersion = version;
120 return true;
121}
122
123std::optional<uint32_t> RpcSession::getProtocolVersion() {
124 std::lock_guard<std::mutex> _l(mMutex);
125 return mProtocolVersion;
126}
127
Steven Moreland2372f9d2021-08-05 15:42:01 -0700128status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000129 return setupSocketClient(UnixSocketAddress(path));
130}
131
Steven Moreland2372f9d2021-08-05 15:42:01 -0700132status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133 return setupSocketClient(VsockSocketAddress(cid, port));
134}
135
Steven Moreland2372f9d2021-08-05 15:42:01 -0700136status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000137 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700138 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000139 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
140 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700141 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000142 }
143 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700144 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145}
146
Steven Moreland2372f9d2021-08-05 15:42:01 -0700147status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Steven Moreland826367f2021-09-10 14:05:31 -0700148 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700149 // std::move'd from fd becomes -1 (!ok())
150 if (!fd.ok()) {
151 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700152 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700153 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700154 if (auto res = setNonBlocking(fd); !res.ok()) {
155 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
156 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
157 }
Steven Moreland4198a122021-08-03 17:37:58 -0700158 return initAndAddConnection(std::move(fd), sessionId, incoming);
159 });
160}
161
Steven Moreland2372f9d2021-08-05 15:42:01 -0700162status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700163 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700164 if (auto status = initShutdownTrigger(); status != OK) return status;
165
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000166 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
167
168 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700169 int savedErrno = errno;
170 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
171 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000172 }
173
Yifan Hongecf937d2021-08-11 17:29:28 -0700174 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700175 if (server == nullptr) {
176 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700177 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700178 }
179 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180}
181
182sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000183 ExclusiveConnection connection;
184 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
185 ConnectionUse::CLIENT, &connection);
186 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000187 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188}
189
Steven Moreland1be91352021-05-11 22:12:15 +0000190status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000191 ExclusiveConnection connection;
192 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
193 ConnectionUse::CLIENT, &connection);
194 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000195 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000196}
197
Steven Morelandc9d7b532021-06-04 20:57:41 +0000198bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000199 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000200 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000201
202 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000203
Steven Morelandc9d7b532021-06-04 20:57:41 +0000204 if (wait) {
205 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700206 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700207
Steven Morelandc9d7b532021-06-04 20:57:41 +0000208 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
209 }
210
211 _l.unlock();
212 mState->clear();
213
Steven Moreland659416d2021-05-11 00:47:50 +0000214 return true;
215}
216
Steven Morelandf5174272021-05-25 00:39:28 +0000217status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000218 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000219 ExclusiveConnection connection;
220 status_t status =
221 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
222 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
223 : ConnectionUse::CLIENT,
224 &connection);
225 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000226 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000227 sp<RpcSession>::fromExisting(this), reply, flags);
228}
229
Steven Moreland4f622fe2021-09-13 17:38:09 -0700230status_t RpcSession::sendDecStrong(const BpBinder* binder) {
231 return sendDecStrong(binder->getPrivateAccessor().rpcAddress());
232}
233
Steven Moreland5623d1a2021-09-10 15:45:34 -0700234status_t RpcSession::sendDecStrong(uint64_t address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000235 ExclusiveConnection connection;
236 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
237 ConnectionUse::CLIENT_REFCOUNT, &connection);
238 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000239 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000240}
241
242status_t RpcSession::readId() {
243 {
244 std::lock_guard<std::mutex> _l(mMutex);
245 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
246 }
247
Steven Moreland195edb82021-06-08 02:44:39 +0000248 ExclusiveConnection connection;
249 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
250 ConnectionUse::CLIENT, &connection);
251 if (status != OK) return status;
252
Steven Moreland826367f2021-09-10 14:05:31 -0700253 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000254 if (status != OK) return status;
255
Steven Moreland826367f2021-09-10 14:05:31 -0700256 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
257 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000258 return OK;
259}
260
Steven Morelanddd67b942021-07-23 17:15:41 -0700261void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000262 const sp<RpcSession>& session) {
263 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000264}
265
Steven Moreland19fc9f72021-06-10 03:57:30 +0000266void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000267 mCv.notify_all();
268}
269
Steven Moreland791e4662021-09-13 15:22:58 -0700270void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
271 const sp<RpcSession>& session) {
272 while (session->mIncomingConnections.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000273 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700274 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
275 "still.",
276 session->mIncomingConnections.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000277 }
278 }
279}
280
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000281void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000282 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283
Steven Morelanda63ff932021-05-12 00:03:15 +0000284 {
285 std::lock_guard<std::mutex> _l(mMutex);
286 mThreads[thread.get_id()] = std::move(thread);
287 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000288}
Steven Morelanda63ff932021-05-12 00:03:15 +0000289
Yifan Hong702115c2021-06-24 15:39:18 -0700290RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
291 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292 // must be registered to allow arbitrary client code executing commands to
293 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700294 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295
Steven Morelanddd67b942021-07-23 17:15:41 -0700296 status_t status;
297
298 if (connection == nullptr) {
299 status = DEAD_OBJECT;
300 } else {
301 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
302 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000303
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000304 return PreJoinSetupResult{
305 .connection = std::move(connection),
306 .status = status,
307 };
308}
309
Yifan Hong194acf22021-06-29 18:44:56 -0700310namespace {
311// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
312// Android Runtime doesn't exist, no-op.
313class JavaThreadAttacher {
314public:
315 JavaThreadAttacher() {
316 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
317 // libbinder.
318 auto vm = getJavaVM();
319 if (vm == nullptr) return;
320
321 char threadName[16];
322 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
323 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
324 memcpy(threadName, defaultThreadName,
325 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
326 }
327 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
328 JavaVMAttachArgs args;
329 args.version = JNI_VERSION_1_2;
330 args.name = threadName;
331 args.group = nullptr;
332 JNIEnv* env;
333
334 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
335 "Cannot attach thread %s to JVM", threadName);
336 mAttached = true;
337 }
338 ~JavaThreadAttacher() {
339 if (!mAttached) return;
340 auto vm = getJavaVM();
341 LOG_ALWAYS_FATAL_IF(vm == nullptr,
342 "Unable to detach thread. No JavaVM, but it was present before!");
343
344 LOG_RPC_DETAIL("Detaching current thread from JVM");
345 if (vm->DetachCurrentThread() != JNI_OK) {
346 mAttached = false;
347 } else {
348 ALOGW("Unable to detach current thread from JVM");
349 }
350 }
351
352private:
353 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
354 bool mAttached = false;
355
356 static JavaVM* getJavaVM() {
357 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
358 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
359 if (fn == nullptr) return nullptr;
360 return fn();
361 }
362};
363} // namespace
364
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000365void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
366 sp<RpcConnection>& connection = setupResult.connection;
367
368 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700369 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700370 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000371 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000372 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000373 RpcState::CommandType::ANY);
374 if (status != OK) {
375 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
376 statusToString(status).c_str());
377 break;
378 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000380 } else {
381 ALOGE("Connection failed to init, closing with status %s",
382 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000383 }
384
Steven Moreland659416d2021-05-11 00:47:50 +0000385 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000386 {
Steven Moreland659416d2021-05-11 00:47:50 +0000387 std::lock_guard<std::mutex> _l(session->mMutex);
388 auto it = session->mThreads.find(std::this_thread::get_id());
389 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000390 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000391 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000392
Steven Moreland659416d2021-05-11 00:47:50 +0000393 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000394 }
395
Steven Morelanddd67b942021-07-23 17:15:41 -0700396 // done after all cleanup, since session shutdown progresses via callbacks here
397 if (connection != nullptr) {
398 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
399 "bad state: connection object guaranteed to be in list");
400 }
401
Steven Moreland659416d2021-05-11 00:47:50 +0000402 session = nullptr;
403
404 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000405 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000406 }
407}
408
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000409sp<RpcServer> RpcSession::server() {
410 RpcServer* unsafeServer = mForServer.unsafe_get();
411 sp<RpcServer> server = mForServer.promote();
412
413 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
414 "wp<> is to avoid strong cycle only");
415 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416}
417
Steven Moreland826367f2021-09-10 14:05:31 -0700418status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
419 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 {
421 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000422 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000423 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000424 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000425 }
Yifan Hong832521e2021-08-05 14:55:40 -0700426 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000427
Steven Moreland826367f2021-09-10 14:05:31 -0700428 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429
Steven Morelandbf57bce2021-07-26 15:26:12 -0700430 {
431 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700432 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
433 ConnectionUse::CLIENT, &connection);
434 status != OK)
435 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700436
437 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700438 if (status_t status =
439 state()->readNewSessionResponse(connection.get(),
440 sp<RpcSession>::fromExisting(this), &version);
441 status != OK)
442 return status;
443 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700444 }
445
Steven Morelanda5036f02021-06-08 02:26:57 +0000446 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000449 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700450 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700452 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000453 }
454
455 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700456 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000457 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700458 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000459 }
460
Steven Morelanda5036f02021-06-08 02:26:57 +0000461 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000462 // instead of all at once - the other side should be responsible for setting
463 // up additional connections. We need to create at least one (unless 0 are
464 // requested to be set) in order to allow the other side to reliably make
465 // any requests at all.
466
Steven Moreland4198a122021-08-03 17:37:58 -0700467 // we've already setup one client
468 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700469 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700470 }
471
Steven Moreland103424e2021-06-02 18:16:19 +0000472 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700473 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000474 }
475
Steven Moreland2372f9d2021-08-05 15:42:01 -0700476 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477}
478
Steven Moreland2372f9d2021-08-05 15:42:01 -0700479status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700480 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700481 return setupOneSocketConnection(addr, sessionId, incoming);
482 });
483}
484
Steven Moreland2372f9d2021-08-05 15:42:01 -0700485status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700486 const std::vector<uint8_t>& sessionId,
487 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000488 for (size_t tries = 0; tries < 5; tries++) {
489 if (tries > 0) usleep(10000);
490
Yifan Hongb675ffe2021-08-05 16:37:17 -0700491 unique_fd serverFd(TEMP_FAILURE_RETRY(
492 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000493 if (serverFd == -1) {
494 int savedErrno = errno;
495 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
496 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700497 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000498 }
499
500 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700501 int connErrno = errno;
502 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
503 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
504 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
505 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
506 if (pollStatus != OK) {
507 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
508 statusToString(pollStatus).c_str());
509 return pollStatus;
510 }
511 // Set connErrno to the errno that connect() would have set if the fd were blocking.
512 socklen_t connErrnoLen = sizeof(connErrno);
513 int ret =
514 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
515 if (ret == -1) {
516 int savedErrno = errno;
517 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
518 "(Original error from connect() is: %s)",
519 strerror(savedErrno), strerror(connErrno));
520 return -savedErrno;
521 }
522 // Retrieved the real connErrno as if connect() was called with a blocking socket
523 // fd. Continue checking connErrno.
524 }
525 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000526 ALOGW("Connection reset on %s", addr.toString().c_str());
527 continue;
528 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700529 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
530 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700531 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700532 strerror(connErrno));
533 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700534 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000535 }
Yifan Hong702115c2021-06-24 15:39:18 -0700536 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
537
Steven Moreland4198a122021-08-03 17:37:58 -0700538 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000539 }
540
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000541 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700542 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543}
544
Steven Moreland826367f2021-09-10 14:05:31 -0700545status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700547 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700548 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700549 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700550 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700551 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700552 }
553
554 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
555
Steven Moreland826367f2021-09-10 14:05:31 -0700556 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
557 ALOGE("Session ID too big %zu", sessionId.size());
558 return BAD_VALUE;
559 }
560
Steven Moreland4198a122021-08-03 17:37:58 -0700561 RpcConnectionHeader header{
562 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
563 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700564 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700565 };
Steven Moreland4198a122021-08-03 17:37:58 -0700566
Steven Moreland826367f2021-09-10 14:05:31 -0700567 if (incoming) {
568 header.options |= RPC_CONNECTION_OPTION_INCOMING;
569 }
Steven Moreland4198a122021-08-03 17:37:58 -0700570
Yifan Hong8c950422021-08-05 17:13:55 -0700571 auto sendHeaderStatus =
572 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
573 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700574 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700575 statusToString(sendHeaderStatus).c_str());
576 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700577 }
578
Steven Moreland826367f2021-09-10 14:05:31 -0700579 if (sessionId.size() > 0) {
580 auto sendSessionIdStatus =
581 server->interruptableWriteFully(mShutdownTrigger.get(), sessionId.data(),
582 sessionId.size());
583 if (sendSessionIdStatus != OK) {
584 ALOGE("Could not write session ID ('%s') to socket: %s",
585 base::HexString(sessionId.data(), sessionId.size()).c_str(),
586 statusToString(sendSessionIdStatus).c_str());
587 return sendSessionIdStatus;
588 }
589 }
590
Steven Moreland4198a122021-08-03 17:37:58 -0700591 LOG_RPC_DETAIL("Socket at client: header sent");
592
593 if (incoming) {
594 return addIncomingConnection(std::move(server));
595 } else {
596 return addOutgoingConnection(std::move(server), true /*init*/);
597 }
598}
599
Steven Moreland2372f9d2021-08-05 15:42:01 -0700600status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000601 std::mutex mutex;
602 std::condition_variable joinCv;
603 std::unique_lock<std::mutex> lock(mutex);
604 std::thread thread;
605 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
606 bool ownershipTransferred = false;
607 thread = std::thread([&]() {
608 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700609 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000610 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
611 sp<RpcSession> session = thiz;
612 session->preJoinThreadOwnership(std::move(thread));
613
614 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700615 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000616
617 ownershipTransferred = true;
618 threadLock.unlock();
619 joinCv.notify_one();
620 // do not use & vars below
621
622 RpcSession::join(std::move(session), std::move(setupResult));
623 });
624 joinCv.wait(lock, [&] { return ownershipTransferred; });
625 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700626 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000627}
628
Yifan Hong832521e2021-08-05 14:55:40 -0700629status_t RpcSession::initShutdownTrigger() {
630 // first client connection added, but setForServer not called, so
631 // initializaing for a client.
632 if (mShutdownTrigger == nullptr) {
633 mShutdownTrigger = FdTrigger::make();
634 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
635 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
636 }
637 return OK;
638}
639
Steven Moreland2372f9d2021-08-05 15:42:01 -0700640status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000641 sp<RpcConnection> connection = sp<RpcConnection>::make();
642 {
643 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700644 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000645 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000646 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000647 }
648
Steven Morelandb86e26b2021-06-12 00:35:58 +0000649 status_t status = OK;
650 if (init) {
651 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
652 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000653
654 {
655 std::lock_guard<std::mutex> _l(mMutex);
656 connection->exclusiveTid = std::nullopt;
657 }
658
Steven Moreland2372f9d2021-08-05 15:42:01 -0700659 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000660}
661
Steven Morelanda8b44292021-06-08 01:27:53 +0000662bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland826367f2021-09-10 14:05:31 -0700663 const std::vector<uint8_t>& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000664 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
665 LOG_ALWAYS_FATAL_IF(server == nullptr);
666 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
667 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000668 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000669
670 mShutdownTrigger = FdTrigger::make();
671 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000672
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000673 mId = sessionId;
674 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000675 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000676 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677}
678
Yifan Hong702115c2021-06-24 15:39:18 -0700679sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
680 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000681 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700682
Steven Moreland132d5bf2021-08-03 16:13:24 -0700683 if (mIncomingConnections.size() >= mMaxThreads) {
684 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
685 mIncomingConnections.size(), mMaxThreads);
686 return nullptr;
687 }
688
Steven Morelanddd67b942021-07-23 17:15:41 -0700689 // Don't accept any more connections, some have shutdown. Usually this
690 // happens when new connections are still being established as part of a
691 // very short-lived session which shuts down after it already started
692 // accepting new connections.
693 if (mIncomingConnections.size() < mMaxIncomingConnections) {
694 return nullptr;
695 }
696
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000697 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700698 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000699 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700700
Steven Moreland19fc9f72021-06-10 03:57:30 +0000701 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700702 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000703
704 return session;
705}
706
Steven Moreland19fc9f72021-06-10 03:57:30 +0000707bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700708 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000709 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
710 it != mIncomingConnections.end()) {
711 mIncomingConnections.erase(it);
712 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000713 sp<EventListener> listener = mEventListener.promote();
714 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700715 _l.unlock();
716 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000717 }
Steven Morelandee78e762021-05-05 21:12:51 +0000718 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000719 return true;
720 }
721 return false;
722}
723
Yifan Hongecf937d2021-08-11 17:29:28 -0700724std::string RpcSession::getCertificate(CertificateFormat format) {
725 return mCtx->getCertificate(format);
726}
727
Steven Moreland195edb82021-06-08 02:44:39 +0000728status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
729 ExclusiveConnection* connection) {
730 connection->mSession = session;
731 connection->mConnection = nullptr;
732 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733
Steven Moreland195edb82021-06-08 02:44:39 +0000734 pid_t tid = gettid();
735 std::unique_lock<std::mutex> _l(session->mMutex);
736
737 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000738 while (true) {
739 sp<RpcConnection> exclusive;
740 sp<RpcConnection> available;
741
742 // CHECK FOR DEDICATED CLIENT SOCKET
743 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000744 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000745 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
746 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747
748 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000749 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000750 //
751 // Imagine we have more than one thread in play, and a single thread
752 // sends a synchronous, then an asynchronous command. Imagine the
753 // asynchronous command is sent on the first client connection. Then, if
754 // we naively send a synchronous command to that same connection, the
755 // thread on the far side might be busy processing the asynchronous
756 // command. So, we move to considering the second available thread
757 // for subsequent calls.
758 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000759 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
760 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000761 }
762
Steven Morelandc7d40132021-06-10 03:42:11 +0000763 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000764 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000765 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000767 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
768 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000769
770 // asynchronous calls cannot be nested, we currently allow ref count
771 // calls to be nested (so that you can use this without having extra
772 // threads). Note 'drainCommands' is used so that these ref counts can't
773 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000774 if (exclusiveIncoming != nullptr) {
775 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000776 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000777 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000778 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
779 // prefer available socket, but if we don't have one, don't
780 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000781 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000782 }
783 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000784 }
785
Steven Moreland85e067b2021-05-26 17:43:53 +0000786 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000787 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000788 connection->mConnection = exclusive;
789 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000790 break;
791 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000792 connection->mConnection = available;
793 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000794 break;
795 }
796
Steven Moreland19fc9f72021-06-10 03:57:30 +0000797 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000798 ALOGE("Session has no client connections. This is required for an RPC server to make "
799 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
800 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000801 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000802 return WOULD_BLOCK;
803 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000804
Steven Moreland85e067b2021-05-26 17:43:53 +0000805 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000806 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000807 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000808 }
Steven Moreland195edb82021-06-08 02:44:39 +0000809 session->mWaitingThreads--;
810
811 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812}
813
814void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
815 sp<RpcConnection>* available,
816 std::vector<sp<RpcConnection>>& sockets,
817 size_t socketsIndexHint) {
818 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
819 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
820
821 if (*exclusive != nullptr) return; // consistent with break below
822
823 for (size_t i = 0; i < sockets.size(); i++) {
824 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
825
Steven Moreland85e067b2021-05-26 17:43:53 +0000826 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000827 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
828 *available = socket;
829 continue;
830 }
831
Steven Moreland85e067b2021-05-26 17:43:53 +0000832 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000833 // (nested transactions)
834 if (exclusive && socket->exclusiveTid == tid) {
835 *exclusive = socket;
836 break; // consistent with return above
837 }
838 }
839}
840
841RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000842 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000843 // is using this fd, and it retains the right to it. So, we don't give up
844 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000845 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000846 std::unique_lock<std::mutex> _l(mSession->mMutex);
847 mConnection->exclusiveTid = std::nullopt;
848 if (mSession->mWaitingThreads > 0) {
849 _l.unlock();
850 mSession->mAvailableConnectionCv.notify_one();
851 }
852 }
853}
854
855} // namespace android