blob: cd21a91d2cdf30adb6ad74b1ae8cbdbd1ca55eca [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 Moreland12af6f72023-03-07 15:14:25 +000023#include <netinet/tcp.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000024#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland4f622fe2021-09-13 17:38:09 -070029#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000030#include <binder/Functional.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000032#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070033#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/Stability.h>
35#include <utils/String8.h>
36
Andrei Homescu9b58a462022-07-28 02:26:46 +000037#include "BuildFlags.h"
Yifan Hong8c950422021-08-05 17:13:55 -070038#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000039#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000040#include "RpcSocketAddress.h"
41#include "RpcState.h"
David Brazdil21c887c2022-09-23 12:25:18 +010042#include "RpcTransportUtils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000043#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070044#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000046#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070047#include <jni.h>
Jeongik Cha0c47d452022-10-20 00:07:55 +090048extern "C" JavaVM* AndroidRuntimeGetJavaVM();
Yifan Hongd258e682021-11-01 18:34:42 -070049#endif
50
Steven Morelandbdb53ab2021-05-05 17:57:41 +000051namespace android {
52
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000053using namespace android::binder::impl;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070054using android::binder::borrowed_fd;
55using android::binder::unique_fd;
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056
Yifan Hongecf937d2021-08-11 17:29:28 -070057RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000058 LOG_RPC_DETAIL("RpcSession created %p", this);
59
Steven Moreland27a8bc72021-09-29 16:07:41 -070060 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000061}
62RpcSession::~RpcSession() {
63 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
64
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000065 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070066 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000067 "Should not be able to destroy a session with servers in use.");
68}
69
Yifan Hongecf937d2021-08-11 17:29:28 -070070sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070071 // Default is without TLS.
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +000072 return make(binder::os::makeDefaultRpcTransportCtxFactory());
Yifan Hongecf937d2021-08-11 17:29:28 -070073}
74
Yifan Hongfdd9f692021-09-09 15:12:52 -070075sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070076 auto ctx = rpcTransportCtxFactory->newClientCtx();
77 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070078 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000079}
80
Yifan Hong10423062021-10-08 16:26:32 -070081void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000082 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000083 LOG_ALWAYS_FATAL_IF(mStartedSetup,
84 "Must set max incoming threads before setting up connections");
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() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000089 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070090 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000091}
92
Steven Morelande65f73c2023-03-04 01:34:50 +000093void RpcSession::setMaxOutgoingConnections(size_t connections) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000094 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000095 LOG_ALWAYS_FATAL_IF(mStartedSetup,
96 "Must set max outgoing threads before setting up connections");
Steven Morelande65f73c2023-03-04 01:34:50 +000097 mMaxOutgoingConnections = connections;
Yifan Hong1f44f982021-10-08 17:16:47 -070098}
99
100size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000101 RpcMutexLockGuard _l(mMutex);
Steven Morelande65f73c2023-03-04 01:34:50 +0000102 return mMaxOutgoingConnections;
Yifan Hong1f44f982021-10-08 17:16:47 -0700103}
104
Andrei Homescu9b58a462022-07-28 02:26:46 +0000105bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000106 if (!RpcState::validateProtocolVersion(version)) {
Steven Morelandbf57bce2021-07-26 15:26:12 -0700107 return false;
108 }
109
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000110 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000111 LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
112 "Must set protocol version before setting up connections");
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
Andrei Homescu9b58a462022-07-28 02:26:46 +0000123bool RpcSession::setProtocolVersion(uint32_t version) {
124 return setProtocolVersionInternal(version, true);
125}
126
Steven Morelandbf57bce2021-07-26 15:26:12 -0700127std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000128 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700129 return mProtocolVersion;
130}
131
Frederick Mayle69a0c992022-05-26 20:38:39 +0000132void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
Andrei Homescu9b58a462022-07-28 02:26:46 +0000133 RpcMutexLockGuard _l(mMutex);
134 LOG_ALWAYS_FATAL_IF(mStartedSetup,
135 "Must set file descriptor transport mode before setting up connections");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000136 mFileDescriptorTransportMode = mode;
137}
138
139RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
140 return mFileDescriptorTransportMode;
141}
142
Steven Moreland2372f9d2021-08-05 15:42:01 -0700143status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144 return setupSocketClient(UnixSocketAddress(path));
145}
146
David Brazdil21c887c2022-09-23 12:25:18 +0100147status_t RpcSession::setupUnixDomainSocketBootstrapClient(unique_fd bootstrapFd) {
148 mBootstrapTransport =
149 mCtx->newTransport(RpcTransportFd(std::move(bootstrapFd)), mShutdownTrigger.get());
150 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
151 int socks[2];
152 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, socks) < 0) {
153 int savedErrno = errno;
154 ALOGE("Failed socketpair: %s", strerror(savedErrno));
155 return -savedErrno;
156 }
157 unique_fd clientFd(socks[0]), serverFd(socks[1]);
158
159 int zero = 0;
160 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700161 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100162 fds.push_back(std::move(serverFd));
163
164 status_t status = mBootstrapTransport->interruptableWriteFully(mShutdownTrigger.get(), &iov,
165 1, std::nullopt, &fds);
166 if (status != OK) {
167 ALOGE("Failed to send fd over bootstrap transport: %s", strerror(-status));
168 return status;
169 }
170
171 return initAndAddConnection(RpcTransportFd(std::move(clientFd)), sessionId, incoming);
172 });
173}
174
Steven Moreland2372f9d2021-08-05 15:42:01 -0700175status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000176 return setupSocketClient(VsockSocketAddress(cid, port));
177}
178
Steven Moreland2372f9d2021-08-05 15:42:01 -0700179status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700181 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000182 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
183 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700184 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185 }
186 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 -0700187 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188}
189
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700190status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000191 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700192 if (!fd.ok()) {
193 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700194 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700195 }
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700196 if (status_t res = binder::os::setNonBlocking(fd); res != OK) return res;
Pawan49d74cb2022-08-03 21:19:11 +0000197
Pawan3e0061c2022-08-26 21:08:34 +0000198 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000199 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000200 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
201 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700202 });
203}
204
Steven Moreland2372f9d2021-08-05 15:42:01 -0700205status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700206 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700207 if (auto status = initShutdownTrigger(); status != OK) return status;
208
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000209 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
210
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -0800211 if (!serverFd.ok()) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700212 int savedErrno = errno;
213 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
214 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215 }
216
Pawan3e0061c2022-08-26 21:08:34 +0000217 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000218 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700219 if (server == nullptr) {
220 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700221 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700222 }
223 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000224}
225
226sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000227 ExclusiveConnection connection;
228 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
229 ConnectionUse::CLIENT, &connection);
230 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000231 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000232}
233
Steven Moreland1be91352021-05-11 22:12:15 +0000234status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000235 ExclusiveConnection connection;
236 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
237 ConnectionUse::CLIENT, &connection);
238 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000239 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000240}
241
Steven Morelandc9d7b532021-06-04 20:57:41 +0000242bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000243 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000244 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000245
246 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000247
Steven Morelandc9d7b532021-06-04 20:57:41 +0000248 if (wait) {
249 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700250 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700251
Steven Morelanda59937e2021-10-04 17:42:30 -0700252 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000253 }
254
255 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000256
Devin Moore66d5b7a2022-07-07 21:42:10 +0000257 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
258 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
259 statusToString(res).c_str());
260 }
261
Steven Moreland27a8bc72021-09-29 16:07:41 -0700262 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000263
Steven Moreland659416d2021-05-11 00:47:50 +0000264 return true;
265}
266
Steven Morelandf5174272021-05-25 00:39:28 +0000267status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000268 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000269 ExclusiveConnection connection;
270 status_t status =
271 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
272 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
273 : ConnectionUse::CLIENT,
274 &connection);
275 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000276 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000277 sp<RpcSession>::fromExisting(this), reply, flags);
278}
279
Steven Moreland4f622fe2021-09-13 17:38:09 -0700280status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000281 // target is 0 because this is used to free BpBinder objects
282 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700283}
284
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000285status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000286 ExclusiveConnection connection;
287 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
288 ConnectionUse::CLIENT_REFCOUNT, &connection);
289 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000290 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
291 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292}
293
294status_t RpcSession::readId() {
295 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000296 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000297 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
298 }
299
Steven Moreland195edb82021-06-08 02:44:39 +0000300 ExclusiveConnection connection;
301 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
302 ConnectionUse::CLIENT, &connection);
303 if (status != OK) return status;
304
Steven Moreland826367f2021-09-10 14:05:31 -0700305 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 if (status != OK) return status;
307
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000308 LOG_RPC_DETAIL("RpcSession %p has id %s", this, HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309 return OK;
310}
311
Steven Morelanddd67b942021-07-23 17:15:41 -0700312void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000313 const sp<RpcSession>& session) {
314 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000315}
316
Steven Moreland19fc9f72021-06-10 03:57:30 +0000317void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000318 mShutdownCount += 1;
Steven Moreland659416d2021-05-11 00:47:50 +0000319 mCv.notify_all();
320}
321
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000322void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700323 const sp<RpcSession>& session) {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000324 while (mShutdownCount < session->mConnections.mMaxIncoming) {
Steven Moreland659416d2021-05-11 00:47:50 +0000325 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700326 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
Steven Moreland8b7a7382022-10-08 04:00:54 +0000327 "still %zu/%zu fully shutdown.",
328 session->mConnections.mIncoming.size(), mShutdownCount.load(),
329 session->mConnections.mMaxIncoming);
Steven Moreland659416d2021-05-11 00:47:50 +0000330 }
331 }
332}
333
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000334void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
335 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000336
Steven Morelanda63ff932021-05-12 00:03:15 +0000337 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000338 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700339 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000340 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000341}
Steven Morelanda63ff932021-05-12 00:03:15 +0000342
Yifan Hong702115c2021-06-24 15:39:18 -0700343RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
344 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345 // must be registered to allow arbitrary client code executing commands to
346 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700347 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348
Steven Morelanddd67b942021-07-23 17:15:41 -0700349 status_t status;
350
351 if (connection == nullptr) {
352 status = DEAD_OBJECT;
353 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700354 status =
355 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700356 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000357
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000358 return PreJoinSetupResult{
359 .connection = std::move(connection),
360 .status = status,
361 };
362}
363
Yifan Hong194acf22021-06-29 18:44:56 -0700364namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000365#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700366class JavaThreadAttacher {};
367#else
Yifan Hong194acf22021-06-29 18:44:56 -0700368// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
369// Android Runtime doesn't exist, no-op.
370class JavaThreadAttacher {
371public:
372 JavaThreadAttacher() {
373 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
374 // libbinder.
375 auto vm = getJavaVM();
376 if (vm == nullptr) return;
377
378 char threadName[16];
379 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
380 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
381 memcpy(threadName, defaultThreadName,
382 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
383 }
384 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
385 JavaVMAttachArgs args;
386 args.version = JNI_VERSION_1_2;
387 args.name = threadName;
388 args.group = nullptr;
389 JNIEnv* env;
390
391 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
392 "Cannot attach thread %s to JVM", threadName);
393 mAttached = true;
394 }
395 ~JavaThreadAttacher() {
396 if (!mAttached) return;
397 auto vm = getJavaVM();
398 LOG_ALWAYS_FATAL_IF(vm == nullptr,
399 "Unable to detach thread. No JavaVM, but it was present before!");
400
401 LOG_RPC_DETAIL("Detaching current thread from JVM");
Steven Morelandd0c9a172022-10-24 15:46:21 +0000402 int ret = vm->DetachCurrentThread();
403 if (ret == JNI_OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700404 mAttached = false;
405 } else {
Steven Morelandd0c9a172022-10-24 15:46:21 +0000406 ALOGW("Unable to detach current thread from JVM (%d)", ret);
Yifan Hong194acf22021-06-29 18:44:56 -0700407 }
408 }
409
410private:
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700411 JavaThreadAttacher(const JavaThreadAttacher&) = delete;
412 void operator=(const JavaThreadAttacher&) = delete;
413
Yifan Hong194acf22021-06-29 18:44:56 -0700414 bool mAttached = false;
415
416 static JavaVM* getJavaVM() {
417 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
418 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
419 if (fn == nullptr) return nullptr;
420 return fn();
421 }
422};
Yifan Hongd258e682021-11-01 18:34:42 -0700423#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700424} // namespace
425
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000426void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
427 sp<RpcConnection>& connection = setupResult.connection;
428
429 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700430 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700431 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000432 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000433 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000434 RpcState::CommandType::ANY);
435 if (status != OK) {
436 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
437 statusToString(status).c_str());
438 break;
439 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000441 } else {
442 ALOGE("Connection failed to init, closing with status %s",
443 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444 }
445
Steven Moreland659416d2021-05-11 00:47:50 +0000446 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000447 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000448 RpcMutexLockGuard _l(session->mMutex);
449 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700450 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000451 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700452 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000453
Steven Moreland659416d2021-05-11 00:47:50 +0000454 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000455 }
456
Steven Morelanddd67b942021-07-23 17:15:41 -0700457 // done after all cleanup, since session shutdown progresses via callbacks here
458 if (connection != nullptr) {
459 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
460 "bad state: connection object guaranteed to be in list");
461 }
462
Steven Moreland659416d2021-05-11 00:47:50 +0000463 session = nullptr;
464
465 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000466 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000467 }
468}
469
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000470sp<RpcServer> RpcSession::server() {
471 RpcServer* unsafeServer = mForServer.unsafe_get();
472 sp<RpcServer> server = mForServer.promote();
473
474 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
475 "wp<> is to avoid strong cycle only");
476 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477}
478
Steven Moreland826367f2021-09-10 14:05:31 -0700479status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
480 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000482 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000483 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
484 mStartedSetup = true;
485
486 if constexpr (!kEnableRpcThreads) {
487 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
488 "Incoming threads are not supported on single-threaded libbinder");
489 // mMaxIncomingThreads should not change from here to its use below,
490 // since we set mStartedSetup==true and setMaxIncomingThreads checks
491 // for that
492 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000493 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700494
Yifan Hong832521e2021-08-05 14:55:40 -0700495 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000496
Steven Moreland27a8bc72021-09-29 16:07:41 -0700497 auto oldProtocolVersion = mProtocolVersion;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000498 auto cleanup = make_scope_guard([&] {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700499 // if any threads are started, shut them down
500 (void)shutdownAndWait(true);
501
502 mShutdownListener = nullptr;
503 mEventListener.clear();
504
505 mId.clear();
506
507 mShutdownTrigger = nullptr;
508 mRpcBinderState = std::make_unique<RpcState>();
509
510 // protocol version may have been downgraded - if we reuse this object
511 // to connect to another server, force that server to request a
512 // downgrade again
513 mProtocolVersion = oldProtocolVersion;
514
Steven Morelanda59937e2021-10-04 17:42:30 -0700515 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000516
517 // clear mStartedSetup so that we can reuse this RpcSession
518 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700519 });
520
Steven Moreland826367f2021-09-10 14:05:31 -0700521 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000522
Steven Morelandbf57bce2021-07-26 15:26:12 -0700523 {
524 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700525 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
526 ConnectionUse::CLIENT, &connection);
527 status != OK)
528 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700529
530 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531 if (status_t status =
532 state()->readNewSessionResponse(connection.get(),
533 sp<RpcSession>::fromExisting(this), &version);
534 status != OK)
535 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000536 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700537 }
538
Steven Morelanda5036f02021-06-08 02:26:57 +0000539 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000541 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000542 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700543 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700545 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 }
547
548 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700549 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700551 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000552 }
553
Steven Morelande65f73c2023-03-04 01:34:50 +0000554 size_t outgoingConnections = std::min(numThreadsAvailable, mMaxOutgoingConnections);
555 ALOGI_IF(outgoingConnections != numThreadsAvailable,
Yifan Hong1f44f982021-10-08 17:16:47 -0700556 "Server hints client to start %zu outgoing threads, but client will only start %zu "
557 "because it is preconfigured to start at most %zu outgoing threads.",
Steven Morelande65f73c2023-03-04 01:34:50 +0000558 numThreadsAvailable, outgoingConnections, mMaxOutgoingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700559
Steven Morelanda5036f02021-06-08 02:26:57 +0000560 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000561 // instead of all at once - the other side should be responsible for setting
562 // up additional connections. We need to create at least one (unless 0 are
563 // requested to be set) in order to allow the other side to reliably make
564 // any requests at all.
565
Steven Moreland4198a122021-08-03 17:37:58 -0700566 // we've already setup one client
Steven Morelande65f73c2023-03-04 01:34:50 +0000567 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing connections (server max: "
568 "%zu) and %zu incoming threads",
569 outgoingConnections, numThreadsAvailable, mMaxIncomingThreads);
570 for (size_t i = 0; i + 1 < outgoingConnections; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700571 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700572 }
573
Yifan Hong10423062021-10-08 16:26:32 -0700574 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700575 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000576 }
577
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000578 cleanup.release();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700579
Steven Moreland2372f9d2021-08-05 15:42:01 -0700580 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000581}
582
Steven Moreland2372f9d2021-08-05 15:42:01 -0700583status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700584 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700585 return setupOneSocketConnection(addr, sessionId, incoming);
586 });
587}
588
Steven Moreland2372f9d2021-08-05 15:42:01 -0700589status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700590 const std::vector<uint8_t>& sessionId,
591 bool incoming) {
Devin Moore18f63752024-08-08 21:01:24 +0000592 RpcTransportFd transportFd;
593 status_t status = singleSocketConnection(addr, mShutdownTrigger, &transportFd);
594 if (status != OK) return status;
595
596 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
597}
598
599status_t singleSocketConnection(const RpcSocketAddress& addr,
600 const std::unique_ptr<FdTrigger>& shutdownTrigger,
601 RpcTransportFd* outFd) {
602 LOG_ALWAYS_FATAL_IF(outFd == nullptr,
603 "There is no reason to call this function without an outFd");
604 LOG_ALWAYS_FATAL_IF(shutdownTrigger == nullptr,
605 "FdTrigger argument is required so we don't get stuck in the connect call "
606 "if the server process shuts down.");
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000607 for (size_t tries = 0; tries < 5; tries++) {
608 if (tries > 0) usleep(10000);
609
Yifan Hongb675ffe2021-08-05 16:37:17 -0700610 unique_fd serverFd(TEMP_FAILURE_RETRY(
611 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -0800612 if (!serverFd.ok()) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000613 int savedErrno = errno;
614 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
615 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700616 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000617 }
618
Steven Moreland12af6f72023-03-07 15:14:25 +0000619 if (addr.addr()->sa_family == AF_INET || addr.addr()->sa_family == AF_INET6) {
620 int noDelay = 1;
621 int result =
622 setsockopt(serverFd.get(), IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay));
623 if (result < 0) {
624 int savedErrno = errno;
625 ALOGE("Could not set TCP_NODELAY on %s: %s", addr.toString().c_str(),
626 strerror(savedErrno));
627 return -savedErrno;
628 }
629 }
630
Pawan3e0061c2022-08-26 21:08:34 +0000631 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000632
633 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700634 int connErrno = errno;
635 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
636 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
637 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Devin Moore18f63752024-08-08 21:01:24 +0000638 status_t pollStatus = shutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700639 if (pollStatus != OK) {
640 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
641 statusToString(pollStatus).c_str());
642 return pollStatus;
643 }
644 // Set connErrno to the errno that connect() would have set if the fd were blocking.
645 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000646 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
647 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700648 if (ret == -1) {
649 int savedErrno = errno;
650 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
651 "(Original error from connect() is: %s)",
652 strerror(savedErrno), strerror(connErrno));
653 return -savedErrno;
654 }
655 // Retrieved the real connErrno as if connect() was called with a blocking socket
656 // fd. Continue checking connErrno.
657 }
658 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000659 ALOGW("Connection reset on %s", addr.toString().c_str());
660 continue;
661 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700662 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
663 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700664 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700665 strerror(connErrno));
666 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700667 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000668 }
Pawan49d74cb2022-08-03 21:19:11 +0000669 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
670 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700671
Devin Moore18f63752024-08-08 21:01:24 +0000672 *outFd = std::move(transportFd);
673 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000674 }
675
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000676 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700677 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000678}
679
Pawan3e0061c2022-08-26 21:08:34 +0000680status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700681 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700682 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700683 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700684 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700685 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700686 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700687 }
688
689 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
690
Steven Moreland826367f2021-09-10 14:05:31 -0700691 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
692 ALOGE("Session ID too big %zu", sessionId.size());
693 return BAD_VALUE;
694 }
695
Steven Moreland4198a122021-08-03 17:37:58 -0700696 RpcConnectionHeader header{
697 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
698 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000699 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700700 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700701 };
Steven Moreland4198a122021-08-03 17:37:58 -0700702
Steven Moreland826367f2021-09-10 14:05:31 -0700703 if (incoming) {
704 header.options |= RPC_CONNECTION_OPTION_INCOMING;
705 }
Steven Moreland4198a122021-08-03 17:37:58 -0700706
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000707 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000708 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
709 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700710 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700711 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700712 statusToString(sendHeaderStatus).c_str());
713 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700714 }
715
Steven Moreland826367f2021-09-10 14:05:31 -0700716 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000717 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
718 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000719 auto sendSessionIdStatus =
720 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
721 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700722 if (sendSessionIdStatus != OK) {
723 ALOGE("Could not write session ID ('%s') to socket: %s",
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000724 HexString(sessionId.data(), sessionId.size()).c_str(),
Steven Moreland826367f2021-09-10 14:05:31 -0700725 statusToString(sendSessionIdStatus).c_str());
726 return sendSessionIdStatus;
727 }
728 }
729
Steven Moreland4198a122021-08-03 17:37:58 -0700730 LOG_RPC_DETAIL("Socket at client: header sent");
731
732 if (incoming) {
733 return addIncomingConnection(std::move(server));
734 } else {
735 return addOutgoingConnection(std::move(server), true /*init*/);
736 }
737}
738
Steven Moreland2372f9d2021-08-05 15:42:01 -0700739status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000740 RpcMutex mutex;
741 RpcConditionVariable joinCv;
742 RpcMutexUniqueLock lock(mutex);
743 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000744 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
745 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000746 thread = RpcMaybeThread([&]() {
747 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700748 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000749 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
750 sp<RpcSession> session = thiz;
751 session->preJoinThreadOwnership(std::move(thread));
752
753 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700754 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000755
756 ownershipTransferred = true;
757 threadLock.unlock();
758 joinCv.notify_one();
759 // do not use & vars below
760
761 RpcSession::join(std::move(session), std::move(setupResult));
762 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000763 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000764 joinCv.wait(lock, [&] { return ownershipTransferred; });
765 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700766 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000767}
768
Yifan Hong832521e2021-08-05 14:55:40 -0700769status_t RpcSession::initShutdownTrigger() {
770 // first client connection added, but setForServer not called, so
771 // initializaing for a client.
772 if (mShutdownTrigger == nullptr) {
773 mShutdownTrigger = FdTrigger::make();
774 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
775 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
776 }
777 return OK;
778}
779
Steven Moreland2372f9d2021-08-05 15:42:01 -0700780status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000781 sp<RpcConnection> connection = sp<RpcConnection>::make();
782 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000783 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700784 connection->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000785 connection->exclusiveTid = binder::os::GetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700786 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000787 }
788
Steven Morelandb86e26b2021-06-12 00:35:58 +0000789 status_t status = OK;
790 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700791 status =
792 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000793 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000794
Andrei Homescuc8490872022-06-23 05:18:51 +0000795 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000796
Steven Moreland2372f9d2021-08-05 15:42:01 -0700797 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000798}
799
Steven Morelanda8b44292021-06-08 01:27:53 +0000800bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700801 const std::vector<uint8_t>& sessionId,
802 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000803 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
804 LOG_ALWAYS_FATAL_IF(server == nullptr);
805 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
806 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000807 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000808 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000809
810 mShutdownTrigger = FdTrigger::make();
811 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000812
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000813 mId = sessionId;
814 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000815 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700816 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000817 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000818}
819
Alice Wang8578f132024-05-03 09:01:56 +0000820void RpcSession::setSessionSpecificRoot(const sp<IBinder>& sessionSpecificRoot) {
Alice Wangc0d50952024-07-19 16:50:10 +0000821 LOG_ALWAYS_FATAL_IF(mSessionSpecificRootObject != nullptr,
822 "Session specific root object already set");
823 LOG_ALWAYS_FATAL_IF(mForServer != nullptr,
824 "Session specific root object cannot be set for a server");
Alice Wang8578f132024-05-03 09:01:56 +0000825 mSessionSpecificRootObject = sessionSpecificRoot;
826}
827
Yifan Hong702115c2021-06-24 15:39:18 -0700828sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
829 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000830 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700831
Yifan Hong10423062021-10-08 16:26:32 -0700832 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700833 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700834 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700835 return nullptr;
836 }
837
Steven Morelanddd67b942021-07-23 17:15:41 -0700838 // Don't accept any more connections, some have shutdown. Usually this
839 // happens when new connections are still being established as part of a
840 // very short-lived session which shuts down after it already started
841 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700842 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700843 return nullptr;
844 }
845
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000846 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700847 session->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000848 session->exclusiveTid = binder::os::GetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700849
Steven Morelanda59937e2021-10-04 17:42:30 -0700850 mConnections.mIncoming.push_back(session);
851 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000852
853 return session;
854}
855
Steven Moreland19fc9f72021-06-10 03:57:30 +0000856bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000857 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700858 if (auto it =
859 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
860 it != mConnections.mIncoming.end()) {
861 mConnections.mIncoming.erase(it);
862 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000863 sp<EventListener> listener = mEventListener.promote();
864 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700865 _l.unlock();
866 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000867 }
Steven Morelandee78e762021-05-05 21:12:51 +0000868 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000869 return true;
870 }
871 return false;
872}
873
Andrei Homescuc8490872022-06-23 05:18:51 +0000874void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000875 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000876 connection->exclusiveTid = std::nullopt;
877 if (mConnections.mWaitingThreads > 0) {
878 _l.unlock();
879 mAvailableConnectionCv.notify_one();
880 }
881}
882
Yifan Hong9734cfc2021-09-13 16:14:09 -0700883std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700884 return mCtx->getCertificate(format);
885}
886
Steven Moreland195edb82021-06-08 02:44:39 +0000887status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
888 ExclusiveConnection* connection) {
889 connection->mSession = session;
890 connection->mConnection = nullptr;
891 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000892
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000893 uint64_t tid = binder::os::GetThreadId();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000894 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000895
Steven Morelanda59937e2021-10-04 17:42:30 -0700896 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000897 while (true) {
898 sp<RpcConnection> exclusive;
899 sp<RpcConnection> available;
900
901 // CHECK FOR DEDICATED CLIENT SOCKET
902 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000903 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700904 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
905 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000906
907 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700908 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000909 //
910 // Imagine we have more than one thread in play, and a single thread
911 // sends a synchronous, then an asynchronous command. Imagine the
912 // asynchronous command is sent on the first client connection. Then, if
913 // we naively send a synchronous command to that same connection, the
914 // thread on the far side might be busy processing the asynchronous
915 // command. So, we move to considering the second available thread
916 // for subsequent calls.
917 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700918 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
919 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000920 }
921
Steven Morelandc7d40132021-06-10 03:42:11 +0000922 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000923 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000924 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000925 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000926 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700927 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000928
929 // asynchronous calls cannot be nested, we currently allow ref count
930 // calls to be nested (so that you can use this without having extra
931 // threads). Note 'drainCommands' is used so that these ref counts can't
932 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000933 if (exclusiveIncoming != nullptr) {
934 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000935 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000936 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000937 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
938 // prefer available socket, but if we don't have one, don't
939 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000940 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000941 }
942 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000943 }
944
Steven Moreland85e067b2021-05-26 17:43:53 +0000945 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000946 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000947 connection->mConnection = exclusive;
948 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000949 break;
950 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000951 connection->mConnection = available;
952 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000953 break;
954 }
955
Steven Morelanda59937e2021-10-04 17:42:30 -0700956 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000957 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
958 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
959 "reason: %d. Incoming connections: %zu. %s.",
960 static_cast<int>(use), session->mConnections.mIncoming.size(),
961 (session->server()
962 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
963 "for the corresponding client"
Steven Morelandfeb13e82023-03-01 01:25:33 +0000964 : "This is a client session, so see "
965 "RpcSession::setMaxOutgoingConnections "
Steven Moreland25d9cc52022-03-10 23:11:56 +0000966 "for this client or RpcServer::setMaxThreads for the corresponding "
967 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000968 return WOULD_BLOCK;
969 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000970
Steven Moreland85e067b2021-05-26 17:43:53 +0000971 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700972 session->mConnections.mOutgoing.size(),
973 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000974 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000975 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700976 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000977
978 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000979}
980
Andrei Homescue922b232022-04-23 03:41:09 +0000981void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000982 sp<RpcConnection>* available,
983 std::vector<sp<RpcConnection>>& sockets,
984 size_t socketsIndexHint) {
985 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
986 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
987
988 if (*exclusive != nullptr) return; // consistent with break below
989
990 for (size_t i = 0; i < sockets.size(); i++) {
991 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
992
Steven Moreland85e067b2021-05-26 17:43:53 +0000993 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000994 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
995 *available = socket;
996 continue;
997 }
998
Steven Moreland85e067b2021-05-26 17:43:53 +0000999 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001000 // (nested transactions)
1001 if (exclusive && socket->exclusiveTid == tid) {
1002 *exclusive = socket;
1003 break; // consistent with return above
1004 }
1005 }
1006}
1007
1008RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +00001009 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001010 // is using this fd, and it retains the right to it. So, we don't give up
1011 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +00001012 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +00001013 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001014 }
1015}
1016
Pawan1c24f9c2022-08-26 23:23:15 +00001017bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
1018 for (const auto& connection : connections) {
1019 if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
1020 return true;
1021 }
1022 }
1023 return false;
1024}
1025
1026bool RpcSession::hasActiveRequests() {
1027 RpcMutexUniqueLock _l(mMutex);
1028 if (hasActiveConnection(mConnections.mIncoming)) {
1029 return true;
1030 }
1031 if (hasActiveConnection(mConnections.mOutgoing)) {
1032 return true;
1033 }
1034 return mConnections.mWaitingThreads != 0;
1035}
1036
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001037} // namespace android