blob: 486b67b62cfcf5717b8752652709a1b62e565ae1 [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>
Steven Moreland27a8bc72021-09-29 16:07:41 -070031#include <android-base/scopeguard.h>
Yifan Hong194acf22021-06-29 18:44:56 -070032#include <android_runtime/vm.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070033#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000035#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070036#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000037#include <binder/Stability.h>
Yifan Hong194acf22021-06-29 18:44:56 -070038#include <jni.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000039#include <utils/String8.h>
40
Yifan Hong8c950422021-08-05 17:13:55 -070041#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000042#include "RpcSocketAddress.h"
43#include "RpcState.h"
44#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070045#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000046
47#ifdef __GLIBC__
48extern "C" pid_t gettid();
49#endif
50
51namespace android {
52
53using base::unique_fd;
54
Yifan Hongecf937d2021-08-11 17:29:28 -070055RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056 LOG_RPC_DETAIL("RpcSession created %p", this);
57
Steven Moreland27a8bc72021-09-29 16:07:41 -070058 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059}
60RpcSession::~RpcSession() {
61 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
62
63 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070064 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000065 "Should not be able to destroy a session with servers in use.");
66}
67
Yifan Hongecf937d2021-08-11 17:29:28 -070068sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070069 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070070 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070071}
72
Yifan Hongfdd9f692021-09-09 15:12:52 -070073sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070074 auto ctx = rpcTransportCtxFactory->newClientCtx();
75 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070076 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077}
78
Yifan Hong10423062021-10-08 16:26:32 -070079void RpcSession::setMaxIncomingThreads(size_t threads) {
Steven Moreland103424e2021-06-02 18:16:19 +000080 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070081 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070082 "Must set max incoming threads before setting up connections, but has %zu "
83 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070084 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070085 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000086}
87
Yifan Hong10423062021-10-08 16:26:32 -070088size_t RpcSession::getMaxIncomingThreads() {
Steven Moreland103424e2021-06-02 18:16:19 +000089 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070090 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000091}
92
Steven Morelandbf57bce2021-07-26 15:26:12 -070093bool RpcSession::setProtocolVersion(uint32_t version) {
94 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
95 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
96 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
97 "is %u).",
98 version, RPC_WIRE_PROTOCOL_VERSION);
99 return false;
100 }
101
102 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700103 if (mProtocolVersion && version > *mProtocolVersion) {
104 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
105 *mProtocolVersion, version);
106 return false;
107 }
108
Steven Morelandbf57bce2021-07-26 15:26:12 -0700109 mProtocolVersion = version;
110 return true;
111}
112
113std::optional<uint32_t> RpcSession::getProtocolVersion() {
114 std::lock_guard<std::mutex> _l(mMutex);
115 return mProtocolVersion;
116}
117
Steven Moreland2372f9d2021-08-05 15:42:01 -0700118status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000119 return setupSocketClient(UnixSocketAddress(path));
120}
121
Steven Moreland2372f9d2021-08-05 15:42:01 -0700122status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000123 return setupSocketClient(VsockSocketAddress(cid, port));
124}
125
Steven Moreland2372f9d2021-08-05 15:42:01 -0700126status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000127 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700128 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000129 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
130 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700131 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000132 }
133 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 -0700134 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000135}
136
Steven Moreland2372f9d2021-08-05 15:42:01 -0700137status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Steven Moreland826367f2021-09-10 14:05:31 -0700138 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700139 // std::move'd from fd becomes -1 (!ok())
140 if (!fd.ok()) {
141 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700142 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700143 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700144 if (auto res = setNonBlocking(fd); !res.ok()) {
145 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
146 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
147 }
Steven Moreland4198a122021-08-03 17:37:58 -0700148 return initAndAddConnection(std::move(fd), sessionId, incoming);
149 });
150}
151
Steven Moreland2372f9d2021-08-05 15:42:01 -0700152status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700153 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700154 if (auto status = initShutdownTrigger(); status != OK) return status;
155
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000156 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
157
158 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700159 int savedErrno = errno;
160 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
161 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 }
163
Yifan Hongecf937d2021-08-11 17:29:28 -0700164 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700165 if (server == nullptr) {
166 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700167 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700168 }
169 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170}
171
172sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000173 ExclusiveConnection connection;
174 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
175 ConnectionUse::CLIENT, &connection);
176 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000177 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178}
179
Steven Moreland1be91352021-05-11 22:12:15 +0000180status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000181 ExclusiveConnection connection;
182 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
183 ConnectionUse::CLIENT, &connection);
184 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000185 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186}
187
Steven Morelandc9d7b532021-06-04 20:57:41 +0000188bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000189 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000190 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000191
192 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000193
Steven Morelandc9d7b532021-06-04 20:57:41 +0000194 if (wait) {
195 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700196 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700197
Steven Morelanda59937e2021-10-04 17:42:30 -0700198 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000199 }
200
201 _l.unlock();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700202 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000203
Steven Moreland659416d2021-05-11 00:47:50 +0000204 return true;
205}
206
Steven Morelandf5174272021-05-25 00:39:28 +0000207status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000208 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000209 ExclusiveConnection connection;
210 status_t status =
211 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
212 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
213 : ConnectionUse::CLIENT,
214 &connection);
215 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000216 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217 sp<RpcSession>::fromExisting(this), reply, flags);
218}
219
Steven Moreland4f622fe2021-09-13 17:38:09 -0700220status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000221 // target is 0 because this is used to free BpBinder objects
222 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700223}
224
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000225status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000226 ExclusiveConnection connection;
227 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
228 ConnectionUse::CLIENT_REFCOUNT, &connection);
229 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000230 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
231 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000232}
233
234status_t RpcSession::readId() {
235 {
236 std::lock_guard<std::mutex> _l(mMutex);
237 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
238 }
239
Steven Moreland195edb82021-06-08 02:44:39 +0000240 ExclusiveConnection connection;
241 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
242 ConnectionUse::CLIENT, &connection);
243 if (status != OK) return status;
244
Steven Moreland826367f2021-09-10 14:05:31 -0700245 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000246 if (status != OK) return status;
247
Steven Moreland826367f2021-09-10 14:05:31 -0700248 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
249 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000250 return OK;
251}
252
Steven Morelanddd67b942021-07-23 17:15:41 -0700253void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000254 const sp<RpcSession>& session) {
255 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000256}
257
Steven Moreland19fc9f72021-06-10 03:57:30 +0000258void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000259 mCv.notify_all();
260}
261
Steven Moreland791e4662021-09-13 15:22:58 -0700262void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
263 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700264 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000265 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700266 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
267 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700268 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000269 }
270 }
271}
272
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000273void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000274 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000275
Steven Morelanda63ff932021-05-12 00:03:15 +0000276 {
277 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700278 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000279 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000280}
Steven Morelanda63ff932021-05-12 00:03:15 +0000281
Yifan Hong702115c2021-06-24 15:39:18 -0700282RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
283 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284 // must be registered to allow arbitrary client code executing commands to
285 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700286 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287
Steven Morelanddd67b942021-07-23 17:15:41 -0700288 status_t status;
289
290 if (connection == nullptr) {
291 status = DEAD_OBJECT;
292 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700293 status =
294 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700295 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000297 return PreJoinSetupResult{
298 .connection = std::move(connection),
299 .status = status,
300 };
301}
302
Yifan Hong194acf22021-06-29 18:44:56 -0700303namespace {
304// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
305// Android Runtime doesn't exist, no-op.
306class JavaThreadAttacher {
307public:
308 JavaThreadAttacher() {
309 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
310 // libbinder.
311 auto vm = getJavaVM();
312 if (vm == nullptr) return;
313
314 char threadName[16];
315 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
316 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
317 memcpy(threadName, defaultThreadName,
318 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
319 }
320 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
321 JavaVMAttachArgs args;
322 args.version = JNI_VERSION_1_2;
323 args.name = threadName;
324 args.group = nullptr;
325 JNIEnv* env;
326
327 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
328 "Cannot attach thread %s to JVM", threadName);
329 mAttached = true;
330 }
331 ~JavaThreadAttacher() {
332 if (!mAttached) return;
333 auto vm = getJavaVM();
334 LOG_ALWAYS_FATAL_IF(vm == nullptr,
335 "Unable to detach thread. No JavaVM, but it was present before!");
336
337 LOG_RPC_DETAIL("Detaching current thread from JVM");
338 if (vm->DetachCurrentThread() != JNI_OK) {
339 mAttached = false;
340 } else {
341 ALOGW("Unable to detach current thread from JVM");
342 }
343 }
344
345private:
346 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
347 bool mAttached = false;
348
349 static JavaVM* getJavaVM() {
350 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
351 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
352 if (fn == nullptr) return nullptr;
353 return fn();
354 }
355};
356} // namespace
357
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000358void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
359 sp<RpcConnection>& connection = setupResult.connection;
360
361 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700362 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700363 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000364 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000365 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000366 RpcState::CommandType::ANY);
367 if (status != OK) {
368 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
369 statusToString(status).c_str());
370 break;
371 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000373 } else {
374 ALOGE("Connection failed to init, closing with status %s",
375 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 }
377
Steven Moreland659416d2021-05-11 00:47:50 +0000378 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000379 {
Steven Moreland659416d2021-05-11 00:47:50 +0000380 std::lock_guard<std::mutex> _l(session->mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700381 auto it = session->mConnections.mThreads.find(std::this_thread::get_id());
382 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000383 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700384 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000385
Steven Moreland659416d2021-05-11 00:47:50 +0000386 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000387 }
388
Steven Morelanddd67b942021-07-23 17:15:41 -0700389 // done after all cleanup, since session shutdown progresses via callbacks here
390 if (connection != nullptr) {
391 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
392 "bad state: connection object guaranteed to be in list");
393 }
394
Steven Moreland659416d2021-05-11 00:47:50 +0000395 session = nullptr;
396
397 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000398 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000399 }
400}
401
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000402sp<RpcServer> RpcSession::server() {
403 RpcServer* unsafeServer = mForServer.unsafe_get();
404 sp<RpcServer> server = mForServer.promote();
405
406 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
407 "wp<> is to avoid strong cycle only");
408 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409}
410
Steven Moreland826367f2021-09-10 14:05:31 -0700411status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
412 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000413 {
414 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700415 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700417 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000418 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700419
Yifan Hong832521e2021-08-05 14:55:40 -0700420 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421
Steven Moreland27a8bc72021-09-29 16:07:41 -0700422 auto oldProtocolVersion = mProtocolVersion;
423 auto cleanup = base::ScopeGuard([&] {
424 // if any threads are started, shut them down
425 (void)shutdownAndWait(true);
426
427 mShutdownListener = nullptr;
428 mEventListener.clear();
429
430 mId.clear();
431
432 mShutdownTrigger = nullptr;
433 mRpcBinderState = std::make_unique<RpcState>();
434
435 // protocol version may have been downgraded - if we reuse this object
436 // to connect to another server, force that server to request a
437 // downgrade again
438 mProtocolVersion = oldProtocolVersion;
439
Steven Morelanda59937e2021-10-04 17:42:30 -0700440 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700441 });
442
Steven Moreland826367f2021-09-10 14:05:31 -0700443 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444
Steven Morelandbf57bce2021-07-26 15:26:12 -0700445 {
446 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700447 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
448 ConnectionUse::CLIENT, &connection);
449 status != OK)
450 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700451
452 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700453 if (status_t status =
454 state()->readNewSessionResponse(connection.get(),
455 sp<RpcSession>::fromExisting(this), &version);
456 status != OK)
457 return status;
458 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700459 }
460
Steven Morelanda5036f02021-06-08 02:26:57 +0000461 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000462 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000463 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000464 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700465 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000466 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700467 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468 }
469
470 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700471 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700473 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000474 }
475
Steven Morelanda5036f02021-06-08 02:26:57 +0000476 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000477 // instead of all at once - the other side should be responsible for setting
478 // up additional connections. We need to create at least one (unless 0 are
479 // requested to be set) in order to allow the other side to reliably make
480 // any requests at all.
481
Steven Moreland4198a122021-08-03 17:37:58 -0700482 // we've already setup one client
483 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700484 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700485 }
486
Yifan Hong10423062021-10-08 16:26:32 -0700487 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700488 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489 }
490
Steven Moreland27a8bc72021-09-29 16:07:41 -0700491 cleanup.Disable();
492
Steven Moreland2372f9d2021-08-05 15:42:01 -0700493 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494}
495
Steven Moreland2372f9d2021-08-05 15:42:01 -0700496status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700497 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700498 return setupOneSocketConnection(addr, sessionId, incoming);
499 });
500}
501
Steven Moreland2372f9d2021-08-05 15:42:01 -0700502status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700503 const std::vector<uint8_t>& sessionId,
504 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000505 for (size_t tries = 0; tries < 5; tries++) {
506 if (tries > 0) usleep(10000);
507
Yifan Hongb675ffe2021-08-05 16:37:17 -0700508 unique_fd serverFd(TEMP_FAILURE_RETRY(
509 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000510 if (serverFd == -1) {
511 int savedErrno = errno;
512 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
513 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700514 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000515 }
516
517 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700518 int connErrno = errno;
519 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
520 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
521 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
522 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
523 if (pollStatus != OK) {
524 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
525 statusToString(pollStatus).c_str());
526 return pollStatus;
527 }
528 // Set connErrno to the errno that connect() would have set if the fd were blocking.
529 socklen_t connErrnoLen = sizeof(connErrno);
530 int ret =
531 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
532 if (ret == -1) {
533 int savedErrno = errno;
534 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
535 "(Original error from connect() is: %s)",
536 strerror(savedErrno), strerror(connErrno));
537 return -savedErrno;
538 }
539 // Retrieved the real connErrno as if connect() was called with a blocking socket
540 // fd. Continue checking connErrno.
541 }
542 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000543 ALOGW("Connection reset on %s", addr.toString().c_str());
544 continue;
545 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700546 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
547 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700548 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700549 strerror(connErrno));
550 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700551 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000552 }
Yifan Hong702115c2021-06-24 15:39:18 -0700553 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
554
Steven Moreland4198a122021-08-03 17:37:58 -0700555 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000556 }
557
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000558 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700559 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560}
561
Steven Moreland826367f2021-09-10 14:05:31 -0700562status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700563 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700564 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700565 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700566 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700567 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700568 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700569 }
570
571 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
572
Steven Moreland826367f2021-09-10 14:05:31 -0700573 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
574 ALOGE("Session ID too big %zu", sessionId.size());
575 return BAD_VALUE;
576 }
577
Steven Moreland4198a122021-08-03 17:37:58 -0700578 RpcConnectionHeader header{
579 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
580 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700581 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700582 };
Steven Moreland4198a122021-08-03 17:37:58 -0700583
Steven Moreland826367f2021-09-10 14:05:31 -0700584 if (incoming) {
585 header.options |= RPC_CONNECTION_OPTION_INCOMING;
586 }
Steven Moreland4198a122021-08-03 17:37:58 -0700587
Yifan Hong8c950422021-08-05 17:13:55 -0700588 auto sendHeaderStatus =
Steven Moreland43921d52021-09-27 17:15:56 -0700589 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header), {});
Yifan Hong8c950422021-08-05 17:13:55 -0700590 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700591 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700592 statusToString(sendHeaderStatus).c_str());
593 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700594 }
595
Steven Moreland826367f2021-09-10 14:05:31 -0700596 if (sessionId.size() > 0) {
597 auto sendSessionIdStatus =
598 server->interruptableWriteFully(mShutdownTrigger.get(), sessionId.data(),
Steven Moreland43921d52021-09-27 17:15:56 -0700599 sessionId.size(), {});
Steven Moreland826367f2021-09-10 14:05:31 -0700600 if (sendSessionIdStatus != OK) {
601 ALOGE("Could not write session ID ('%s') to socket: %s",
602 base::HexString(sessionId.data(), sessionId.size()).c_str(),
603 statusToString(sendSessionIdStatus).c_str());
604 return sendSessionIdStatus;
605 }
606 }
607
Steven Moreland4198a122021-08-03 17:37:58 -0700608 LOG_RPC_DETAIL("Socket at client: header sent");
609
610 if (incoming) {
611 return addIncomingConnection(std::move(server));
612 } else {
613 return addOutgoingConnection(std::move(server), true /*init*/);
614 }
615}
616
Steven Moreland2372f9d2021-08-05 15:42:01 -0700617status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000618 std::mutex mutex;
619 std::condition_variable joinCv;
620 std::unique_lock<std::mutex> lock(mutex);
621 std::thread thread;
622 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
623 bool ownershipTransferred = false;
624 thread = std::thread([&]() {
625 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700626 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000627 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
628 sp<RpcSession> session = thiz;
629 session->preJoinThreadOwnership(std::move(thread));
630
631 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700632 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000633
634 ownershipTransferred = true;
635 threadLock.unlock();
636 joinCv.notify_one();
637 // do not use & vars below
638
639 RpcSession::join(std::move(session), std::move(setupResult));
640 });
641 joinCv.wait(lock, [&] { return ownershipTransferred; });
642 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700643 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000644}
645
Yifan Hong832521e2021-08-05 14:55:40 -0700646status_t RpcSession::initShutdownTrigger() {
647 // first client connection added, but setForServer not called, so
648 // initializaing for a client.
649 if (mShutdownTrigger == nullptr) {
650 mShutdownTrigger = FdTrigger::make();
651 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
652 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
653 }
654 return OK;
655}
656
Steven Moreland2372f9d2021-08-05 15:42:01 -0700657status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000658 sp<RpcConnection> connection = sp<RpcConnection>::make();
659 {
660 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700661 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000662 connection->exclusiveTid = gettid();
Steven Morelanda59937e2021-10-04 17:42:30 -0700663 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000664 }
665
Steven Morelandb86e26b2021-06-12 00:35:58 +0000666 status_t status = OK;
667 if (init) {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700668 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000669 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000670
671 {
672 std::lock_guard<std::mutex> _l(mMutex);
673 connection->exclusiveTid = std::nullopt;
674 }
675
Steven Moreland2372f9d2021-08-05 15:42:01 -0700676 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677}
678
Steven Morelanda8b44292021-06-08 01:27:53 +0000679bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland826367f2021-09-10 14:05:31 -0700680 const std::vector<uint8_t>& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000681 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
682 LOG_ALWAYS_FATAL_IF(server == nullptr);
683 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
684 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000685 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000686
687 mShutdownTrigger = FdTrigger::make();
688 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000689
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000690 mId = sessionId;
691 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000692 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000693 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000694}
695
Yifan Hong702115c2021-06-24 15:39:18 -0700696sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
697 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000698 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700699
Yifan Hong10423062021-10-08 16:26:32 -0700700 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700701 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700702 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700703 return nullptr;
704 }
705
Steven Morelanddd67b942021-07-23 17:15:41 -0700706 // Don't accept any more connections, some have shutdown. Usually this
707 // happens when new connections are still being established as part of a
708 // very short-lived session which shuts down after it already started
709 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700710 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700711 return nullptr;
712 }
713
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000714 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700715 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000716 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700717
Steven Morelanda59937e2021-10-04 17:42:30 -0700718 mConnections.mIncoming.push_back(session);
719 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720
721 return session;
722}
723
Steven Moreland19fc9f72021-06-10 03:57:30 +0000724bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700725 std::unique_lock<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700726 if (auto it =
727 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
728 it != mConnections.mIncoming.end()) {
729 mConnections.mIncoming.erase(it);
730 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000731 sp<EventListener> listener = mEventListener.promote();
732 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700733 _l.unlock();
734 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000735 }
Steven Morelandee78e762021-05-05 21:12:51 +0000736 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000737 return true;
738 }
739 return false;
740}
741
Yifan Hong9734cfc2021-09-13 16:14:09 -0700742std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700743 return mCtx->getCertificate(format);
744}
745
Steven Moreland195edb82021-06-08 02:44:39 +0000746status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
747 ExclusiveConnection* connection) {
748 connection->mSession = session;
749 connection->mConnection = nullptr;
750 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000751
Steven Moreland195edb82021-06-08 02:44:39 +0000752 pid_t tid = gettid();
753 std::unique_lock<std::mutex> _l(session->mMutex);
754
Steven Morelanda59937e2021-10-04 17:42:30 -0700755 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000756 while (true) {
757 sp<RpcConnection> exclusive;
758 sp<RpcConnection> available;
759
760 // CHECK FOR DEDICATED CLIENT SOCKET
761 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000762 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700763 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
764 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000765
766 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700767 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000768 //
769 // Imagine we have more than one thread in play, and a single thread
770 // sends a synchronous, then an asynchronous command. Imagine the
771 // asynchronous command is sent on the first client connection. Then, if
772 // we naively send a synchronous command to that same connection, the
773 // thread on the far side might be busy processing the asynchronous
774 // command. So, we move to considering the second available thread
775 // for subsequent calls.
776 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700777 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
778 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000779 }
780
Steven Morelandc7d40132021-06-10 03:42:11 +0000781 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000782 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000783 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000784 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000785 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700786 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000787
788 // asynchronous calls cannot be nested, we currently allow ref count
789 // calls to be nested (so that you can use this without having extra
790 // threads). Note 'drainCommands' is used so that these ref counts can't
791 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000792 if (exclusiveIncoming != nullptr) {
793 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000794 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000795 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000796 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
797 // prefer available socket, but if we don't have one, don't
798 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000799 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000800 }
801 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000802 }
803
Steven Moreland85e067b2021-05-26 17:43:53 +0000804 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000805 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000806 connection->mConnection = exclusive;
807 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000808 break;
809 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000810 connection->mConnection = available;
811 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812 break;
813 }
814
Steven Morelanda59937e2021-10-04 17:42:30 -0700815 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000816 ALOGE("Session has no client connections. This is required for an RPC server to make "
817 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
818 "connections: %zu",
Steven Morelanda59937e2021-10-04 17:42:30 -0700819 static_cast<int>(use), session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000820 return WOULD_BLOCK;
821 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000822
Steven Moreland85e067b2021-05-26 17:43:53 +0000823 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700824 session->mConnections.mOutgoing.size(),
825 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000826 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000827 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700828 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000829
830 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000831}
832
833void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
834 sp<RpcConnection>* available,
835 std::vector<sp<RpcConnection>>& sockets,
836 size_t socketsIndexHint) {
837 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
838 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
839
840 if (*exclusive != nullptr) return; // consistent with break below
841
842 for (size_t i = 0; i < sockets.size(); i++) {
843 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
844
Steven Moreland85e067b2021-05-26 17:43:53 +0000845 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000846 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
847 *available = socket;
848 continue;
849 }
850
Steven Moreland85e067b2021-05-26 17:43:53 +0000851 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000852 // (nested transactions)
853 if (exclusive && socket->exclusiveTid == tid) {
854 *exclusive = socket;
855 break; // consistent with return above
856 }
857 }
858}
859
860RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000861 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000862 // is using this fd, and it retains the right to it. So, we don't give up
863 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000864 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000865 std::unique_lock<std::mutex> _l(mSession->mMutex);
866 mConnection->exclusiveTid = std::nullopt;
Steven Morelanda59937e2021-10-04 17:42:30 -0700867 if (mSession->mConnections.mWaitingThreads > 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000868 _l.unlock();
869 mSession->mAvailableConnectionCv.notify_one();
870 }
871 }
872}
873
874} // namespace android