blob: edac56ba3b5ada61feb026238d3c1410b1ce8d24 [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 Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Steven Moreland27a8bc72021-09-29 16:07:41 -070030#include <android-base/scopeguard.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070031#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000032#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000033#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/Stability.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000036#include <utils/Compat.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000037#include <utils/String8.h>
38
Andrei Homescu9b58a462022-07-28 02:26:46 +000039#include "BuildFlags.h"
Yifan Hong8c950422021-08-05 17:13:55 -070040#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000041#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000042#include "RpcSocketAddress.h"
43#include "RpcState.h"
David Brazdil21c887c2022-09-23 12:25:18 +010044#include "RpcTransportUtils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070046#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000047
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000048#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070049#include <jni.h>
Jeongik Cha0c47d452022-10-20 00:07:55 +090050extern "C" JavaVM* AndroidRuntimeGetJavaVM();
Yifan Hongd258e682021-11-01 18:34:42 -070051#endif
52
Steven Morelandbdb53ab2021-05-05 17:57:41 +000053namespace android {
54
55using base::unique_fd;
56
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.
Andrei Homescu024727b2022-08-24 23:54:59 +000072 return make(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)};
161 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
162 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
Pawan49d74cb2022-08-03 21:19:11 +0000190status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
191 std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000192 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700193 if (!fd.ok()) {
194 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700195 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700196 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700197 if (auto res = setNonBlocking(fd); !res.ok()) {
198 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
199 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
200 }
Pawan49d74cb2022-08-03 21:19:11 +0000201
Pawan3e0061c2022-08-26 21:08:34 +0000202 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000203 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000204 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
205 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700206 });
207}
208
Steven Moreland2372f9d2021-08-05 15:42:01 -0700209status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700210 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700211 if (auto status = initShutdownTrigger(); status != OK) return status;
212
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
214
215 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700216 int savedErrno = errno;
217 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
218 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000219 }
220
Pawan3e0061c2022-08-26 21:08:34 +0000221 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000222 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700223 if (server == nullptr) {
224 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700225 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700226 }
227 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000228}
229
230sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000231 ExclusiveConnection connection;
232 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
233 ConnectionUse::CLIENT, &connection);
234 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000235 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000236}
237
Steven Moreland1be91352021-05-11 22:12:15 +0000238status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000239 ExclusiveConnection connection;
240 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
241 ConnectionUse::CLIENT, &connection);
242 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000243 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244}
245
Steven Morelandc9d7b532021-06-04 20:57:41 +0000246bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000247 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000248 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000249
250 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000251
Steven Morelandc9d7b532021-06-04 20:57:41 +0000252 if (wait) {
253 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700254 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700255
Steven Morelanda59937e2021-10-04 17:42:30 -0700256 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000257 }
258
259 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000260
Devin Moore66d5b7a2022-07-07 21:42:10 +0000261 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
262 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
263 statusToString(res).c_str());
264 }
265
Steven Moreland27a8bc72021-09-29 16:07:41 -0700266 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000267
Steven Moreland659416d2021-05-11 00:47:50 +0000268 return true;
269}
270
Steven Morelandf5174272021-05-25 00:39:28 +0000271status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000272 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000273 ExclusiveConnection connection;
274 status_t status =
275 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
276 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
277 : ConnectionUse::CLIENT,
278 &connection);
279 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000280 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 sp<RpcSession>::fromExisting(this), reply, flags);
282}
283
Steven Moreland4f622fe2021-09-13 17:38:09 -0700284status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000285 // target is 0 because this is used to free BpBinder objects
286 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700287}
288
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000289status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000290 ExclusiveConnection connection;
291 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
292 ConnectionUse::CLIENT_REFCOUNT, &connection);
293 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000294 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
295 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296}
297
298status_t RpcSession::readId() {
299 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000300 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000301 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
302 }
303
Steven Moreland195edb82021-06-08 02:44:39 +0000304 ExclusiveConnection connection;
305 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
306 ConnectionUse::CLIENT, &connection);
307 if (status != OK) return status;
308
Steven Moreland826367f2021-09-10 14:05:31 -0700309 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 if (status != OK) return status;
311
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000312 LOG_RPC_DETAIL("RpcSession %p has id %s", this, HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313 return OK;
314}
315
Steven Morelanddd67b942021-07-23 17:15:41 -0700316void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000317 const sp<RpcSession>& session) {
318 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000319}
320
Steven Moreland19fc9f72021-06-10 03:57:30 +0000321void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000322 mShutdownCount += 1;
Steven Moreland659416d2021-05-11 00:47:50 +0000323 mCv.notify_all();
324}
325
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000326void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700327 const sp<RpcSession>& session) {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000328 while (mShutdownCount < session->mConnections.mMaxIncoming) {
Steven Moreland659416d2021-05-11 00:47:50 +0000329 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700330 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
Steven Moreland8b7a7382022-10-08 04:00:54 +0000331 "still %zu/%zu fully shutdown.",
332 session->mConnections.mIncoming.size(), mShutdownCount.load(),
333 session->mConnections.mMaxIncoming);
Steven Moreland659416d2021-05-11 00:47:50 +0000334 }
335 }
336}
337
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000338void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
339 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000340
Steven Morelanda63ff932021-05-12 00:03:15 +0000341 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000342 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700343 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000344 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000345}
Steven Morelanda63ff932021-05-12 00:03:15 +0000346
Yifan Hong702115c2021-06-24 15:39:18 -0700347RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
348 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000349 // must be registered to allow arbitrary client code executing commands to
350 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700351 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000352
Steven Morelanddd67b942021-07-23 17:15:41 -0700353 status_t status;
354
355 if (connection == nullptr) {
356 status = DEAD_OBJECT;
357 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700358 status =
359 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700360 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000361
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000362 return PreJoinSetupResult{
363 .connection = std::move(connection),
364 .status = status,
365 };
366}
367
Yifan Hong194acf22021-06-29 18:44:56 -0700368namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000369#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700370class JavaThreadAttacher {};
371#else
Yifan Hong194acf22021-06-29 18:44:56 -0700372// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
373// Android Runtime doesn't exist, no-op.
374class JavaThreadAttacher {
375public:
376 JavaThreadAttacher() {
377 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
378 // libbinder.
379 auto vm = getJavaVM();
380 if (vm == nullptr) return;
381
382 char threadName[16];
383 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
384 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
385 memcpy(threadName, defaultThreadName,
386 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
387 }
388 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
389 JavaVMAttachArgs args;
390 args.version = JNI_VERSION_1_2;
391 args.name = threadName;
392 args.group = nullptr;
393 JNIEnv* env;
394
395 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
396 "Cannot attach thread %s to JVM", threadName);
397 mAttached = true;
398 }
399 ~JavaThreadAttacher() {
400 if (!mAttached) return;
401 auto vm = getJavaVM();
402 LOG_ALWAYS_FATAL_IF(vm == nullptr,
403 "Unable to detach thread. No JavaVM, but it was present before!");
404
405 LOG_RPC_DETAIL("Detaching current thread from JVM");
Steven Morelandd0c9a172022-10-24 15:46:21 +0000406 int ret = vm->DetachCurrentThread();
407 if (ret == JNI_OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700408 mAttached = false;
409 } else {
Steven Morelandd0c9a172022-10-24 15:46:21 +0000410 ALOGW("Unable to detach current thread from JVM (%d)", ret);
Yifan Hong194acf22021-06-29 18:44:56 -0700411 }
412 }
413
414private:
415 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
416 bool mAttached = false;
417
418 static JavaVM* getJavaVM() {
419 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
420 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
421 if (fn == nullptr) return nullptr;
422 return fn();
423 }
424};
Yifan Hongd258e682021-11-01 18:34:42 -0700425#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700426} // namespace
427
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000428void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
429 sp<RpcConnection>& connection = setupResult.connection;
430
431 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700432 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700433 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000434 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000435 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000436 RpcState::CommandType::ANY);
437 if (status != OK) {
438 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
439 statusToString(status).c_str());
440 break;
441 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000443 } else {
444 ALOGE("Connection failed to init, closing with status %s",
445 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 }
447
Steven Moreland659416d2021-05-11 00:47:50 +0000448 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000449 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000450 RpcMutexLockGuard _l(session->mMutex);
451 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700452 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000453 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700454 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000455
Steven Moreland659416d2021-05-11 00:47:50 +0000456 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000457 }
458
Steven Morelanddd67b942021-07-23 17:15:41 -0700459 // done after all cleanup, since session shutdown progresses via callbacks here
460 if (connection != nullptr) {
461 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
462 "bad state: connection object guaranteed to be in list");
463 }
464
Steven Moreland659416d2021-05-11 00:47:50 +0000465 session = nullptr;
466
467 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000468 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000469 }
470}
471
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000472sp<RpcServer> RpcSession::server() {
473 RpcServer* unsafeServer = mForServer.unsafe_get();
474 sp<RpcServer> server = mForServer.promote();
475
476 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
477 "wp<> is to avoid strong cycle only");
478 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479}
480
Steven Moreland826367f2021-09-10 14:05:31 -0700481status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
482 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000484 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000485 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
486 mStartedSetup = true;
487
488 if constexpr (!kEnableRpcThreads) {
489 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
490 "Incoming threads are not supported on single-threaded libbinder");
491 // mMaxIncomingThreads should not change from here to its use below,
492 // since we set mStartedSetup==true and setMaxIncomingThreads checks
493 // for that
494 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700496
Yifan Hong832521e2021-08-05 14:55:40 -0700497 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000498
Steven Moreland27a8bc72021-09-29 16:07:41 -0700499 auto oldProtocolVersion = mProtocolVersion;
500 auto cleanup = base::ScopeGuard([&] {
501 // if any threads are started, shut them down
502 (void)shutdownAndWait(true);
503
504 mShutdownListener = nullptr;
505 mEventListener.clear();
506
507 mId.clear();
508
509 mShutdownTrigger = nullptr;
510 mRpcBinderState = std::make_unique<RpcState>();
511
512 // protocol version may have been downgraded - if we reuse this object
513 // to connect to another server, force that server to request a
514 // downgrade again
515 mProtocolVersion = oldProtocolVersion;
516
Steven Morelanda59937e2021-10-04 17:42:30 -0700517 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000518
519 // clear mStartedSetup so that we can reuse this RpcSession
520 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700521 });
522
Steven Moreland826367f2021-09-10 14:05:31 -0700523 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000524
Steven Morelandbf57bce2021-07-26 15:26:12 -0700525 {
526 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700527 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
528 ConnectionUse::CLIENT, &connection);
529 status != OK)
530 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700531
532 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700533 if (status_t status =
534 state()->readNewSessionResponse(connection.get(),
535 sp<RpcSession>::fromExisting(this), &version);
536 status != OK)
537 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000538 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700539 }
540
Steven Morelanda5036f02021-06-08 02:26:57 +0000541 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000542 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000544 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700545 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700547 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000548 }
549
550 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700551 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000552 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000554 }
555
Steven Morelande65f73c2023-03-04 01:34:50 +0000556 size_t outgoingConnections = std::min(numThreadsAvailable, mMaxOutgoingConnections);
557 ALOGI_IF(outgoingConnections != numThreadsAvailable,
Yifan Hong1f44f982021-10-08 17:16:47 -0700558 "Server hints client to start %zu outgoing threads, but client will only start %zu "
559 "because it is preconfigured to start at most %zu outgoing threads.",
Steven Morelande65f73c2023-03-04 01:34:50 +0000560 numThreadsAvailable, outgoingConnections, mMaxOutgoingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700561
Steven Morelanda5036f02021-06-08 02:26:57 +0000562 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000563 // instead of all at once - the other side should be responsible for setting
564 // up additional connections. We need to create at least one (unless 0 are
565 // requested to be set) in order to allow the other side to reliably make
566 // any requests at all.
567
Steven Moreland4198a122021-08-03 17:37:58 -0700568 // we've already setup one client
Steven Morelande65f73c2023-03-04 01:34:50 +0000569 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing connections (server max: "
570 "%zu) and %zu incoming threads",
571 outgoingConnections, numThreadsAvailable, mMaxIncomingThreads);
572 for (size_t i = 0; i + 1 < outgoingConnections; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700573 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700574 }
575
Yifan Hong10423062021-10-08 16:26:32 -0700576 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700577 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000578 }
579
Steven Moreland27a8bc72021-09-29 16:07:41 -0700580 cleanup.Disable();
581
Steven Moreland2372f9d2021-08-05 15:42:01 -0700582 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000583}
584
Steven Moreland2372f9d2021-08-05 15:42:01 -0700585status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700586 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700587 return setupOneSocketConnection(addr, sessionId, incoming);
588 });
589}
590
Steven Moreland2372f9d2021-08-05 15:42:01 -0700591status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700592 const std::vector<uint8_t>& sessionId,
593 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000594 for (size_t tries = 0; tries < 5; tries++) {
595 if (tries > 0) usleep(10000);
596
Yifan Hongb675ffe2021-08-05 16:37:17 -0700597 unique_fd serverFd(TEMP_FAILURE_RETRY(
598 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000599 if (serverFd == -1) {
600 int savedErrno = errno;
601 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
602 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700603 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000604 }
605
Steven Moreland12af6f72023-03-07 15:14:25 +0000606 if (addr.addr()->sa_family == AF_INET || addr.addr()->sa_family == AF_INET6) {
607 int noDelay = 1;
608 int result =
609 setsockopt(serverFd.get(), IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay));
610 if (result < 0) {
611 int savedErrno = errno;
612 ALOGE("Could not set TCP_NODELAY on %s: %s", addr.toString().c_str(),
613 strerror(savedErrno));
614 return -savedErrno;
615 }
616 }
617
Pawan3e0061c2022-08-26 21:08:34 +0000618 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000619
620 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700621 int connErrno = errno;
622 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
623 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
624 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Pawan49d74cb2022-08-03 21:19:11 +0000625 status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700626 if (pollStatus != OK) {
627 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
628 statusToString(pollStatus).c_str());
629 return pollStatus;
630 }
631 // Set connErrno to the errno that connect() would have set if the fd were blocking.
632 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000633 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
634 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700635 if (ret == -1) {
636 int savedErrno = errno;
637 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
638 "(Original error from connect() is: %s)",
639 strerror(savedErrno), strerror(connErrno));
640 return -savedErrno;
641 }
642 // Retrieved the real connErrno as if connect() was called with a blocking socket
643 // fd. Continue checking connErrno.
644 }
645 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000646 ALOGW("Connection reset on %s", addr.toString().c_str());
647 continue;
648 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700649 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
650 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700651 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700652 strerror(connErrno));
653 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700654 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000655 }
Pawan49d74cb2022-08-03 21:19:11 +0000656 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
657 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700658
Pawan49d74cb2022-08-03 21:19:11 +0000659 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000660 }
661
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000662 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700663 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000664}
665
Pawan3e0061c2022-08-26 21:08:34 +0000666status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700667 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700668 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700669 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700670 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700671 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700672 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700673 }
674
675 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
676
Steven Moreland826367f2021-09-10 14:05:31 -0700677 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
678 ALOGE("Session ID too big %zu", sessionId.size());
679 return BAD_VALUE;
680 }
681
Steven Moreland4198a122021-08-03 17:37:58 -0700682 RpcConnectionHeader header{
683 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
684 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000685 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700686 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700687 };
Steven Moreland4198a122021-08-03 17:37:58 -0700688
Steven Moreland826367f2021-09-10 14:05:31 -0700689 if (incoming) {
690 header.options |= RPC_CONNECTION_OPTION_INCOMING;
691 }
Steven Moreland4198a122021-08-03 17:37:58 -0700692
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000693 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000694 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
695 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700696 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700697 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700698 statusToString(sendHeaderStatus).c_str());
699 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700700 }
701
Steven Moreland826367f2021-09-10 14:05:31 -0700702 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000703 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
704 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000705 auto sendSessionIdStatus =
706 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
707 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700708 if (sendSessionIdStatus != OK) {
709 ALOGE("Could not write session ID ('%s') to socket: %s",
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000710 HexString(sessionId.data(), sessionId.size()).c_str(),
Steven Moreland826367f2021-09-10 14:05:31 -0700711 statusToString(sendSessionIdStatus).c_str());
712 return sendSessionIdStatus;
713 }
714 }
715
Steven Moreland4198a122021-08-03 17:37:58 -0700716 LOG_RPC_DETAIL("Socket at client: header sent");
717
718 if (incoming) {
719 return addIncomingConnection(std::move(server));
720 } else {
721 return addOutgoingConnection(std::move(server), true /*init*/);
722 }
723}
724
Steven Moreland2372f9d2021-08-05 15:42:01 -0700725status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000726 RpcMutex mutex;
727 RpcConditionVariable joinCv;
728 RpcMutexUniqueLock lock(mutex);
729 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000730 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
731 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000732 thread = RpcMaybeThread([&]() {
733 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700734 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000735 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
736 sp<RpcSession> session = thiz;
737 session->preJoinThreadOwnership(std::move(thread));
738
739 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700740 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000741
742 ownershipTransferred = true;
743 threadLock.unlock();
744 joinCv.notify_one();
745 // do not use & vars below
746
747 RpcSession::join(std::move(session), std::move(setupResult));
748 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000749 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000750 joinCv.wait(lock, [&] { return ownershipTransferred; });
751 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700752 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000753}
754
Yifan Hong832521e2021-08-05 14:55:40 -0700755status_t RpcSession::initShutdownTrigger() {
756 // first client connection added, but setForServer not called, so
757 // initializaing for a client.
758 if (mShutdownTrigger == nullptr) {
759 mShutdownTrigger = FdTrigger::make();
760 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
761 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
762 }
763 return OK;
764}
765
Steven Moreland2372f9d2021-08-05 15:42:01 -0700766status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000767 sp<RpcConnection> connection = sp<RpcConnection>::make();
768 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000769 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700770 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000771 connection->exclusiveTid = rpcGetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700772 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000773 }
774
Steven Morelandb86e26b2021-06-12 00:35:58 +0000775 status_t status = OK;
776 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700777 status =
778 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000779 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000780
Andrei Homescuc8490872022-06-23 05:18:51 +0000781 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000782
Steven Moreland2372f9d2021-08-05 15:42:01 -0700783 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000784}
785
Steven Morelanda8b44292021-06-08 01:27:53 +0000786bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700787 const std::vector<uint8_t>& sessionId,
788 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000789 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
790 LOG_ALWAYS_FATAL_IF(server == nullptr);
791 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
792 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000793 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000794 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000795
796 mShutdownTrigger = FdTrigger::make();
797 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000798
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000799 mId = sessionId;
800 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000801 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700802 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000803 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000804}
805
Yifan Hong702115c2021-06-24 15:39:18 -0700806sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
807 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000808 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700809
Yifan Hong10423062021-10-08 16:26:32 -0700810 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700811 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700812 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700813 return nullptr;
814 }
815
Steven Morelanddd67b942021-07-23 17:15:41 -0700816 // Don't accept any more connections, some have shutdown. Usually this
817 // happens when new connections are still being established as part of a
818 // very short-lived session which shuts down after it already started
819 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700820 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700821 return nullptr;
822 }
823
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000824 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700825 session->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000826 session->exclusiveTid = rpcGetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700827
Steven Morelanda59937e2021-10-04 17:42:30 -0700828 mConnections.mIncoming.push_back(session);
829 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000830
831 return session;
832}
833
Steven Moreland19fc9f72021-06-10 03:57:30 +0000834bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000835 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700836 if (auto it =
837 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
838 it != mConnections.mIncoming.end()) {
839 mConnections.mIncoming.erase(it);
840 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000841 sp<EventListener> listener = mEventListener.promote();
842 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700843 _l.unlock();
844 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000845 }
Steven Morelandee78e762021-05-05 21:12:51 +0000846 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000847 return true;
848 }
849 return false;
850}
851
Andrei Homescuc8490872022-06-23 05:18:51 +0000852void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000853 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000854 connection->exclusiveTid = std::nullopt;
855 if (mConnections.mWaitingThreads > 0) {
856 _l.unlock();
857 mAvailableConnectionCv.notify_one();
858 }
859}
860
Yifan Hong9734cfc2021-09-13 16:14:09 -0700861std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700862 return mCtx->getCertificate(format);
863}
864
Steven Moreland195edb82021-06-08 02:44:39 +0000865status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
866 ExclusiveConnection* connection) {
867 connection->mSession = session;
868 connection->mConnection = nullptr;
869 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000870
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000871 uint64_t tid = rpcGetThreadId();
872 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000873
Steven Morelanda59937e2021-10-04 17:42:30 -0700874 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000875 while (true) {
876 sp<RpcConnection> exclusive;
877 sp<RpcConnection> available;
878
879 // CHECK FOR DEDICATED CLIENT SOCKET
880 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000881 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700882 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
883 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000884
885 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700886 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000887 //
888 // Imagine we have more than one thread in play, and a single thread
889 // sends a synchronous, then an asynchronous command. Imagine the
890 // asynchronous command is sent on the first client connection. Then, if
891 // we naively send a synchronous command to that same connection, the
892 // thread on the far side might be busy processing the asynchronous
893 // command. So, we move to considering the second available thread
894 // for subsequent calls.
895 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700896 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
897 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000898 }
899
Steven Morelandc7d40132021-06-10 03:42:11 +0000900 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000901 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000902 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000903 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000904 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700905 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000906
907 // asynchronous calls cannot be nested, we currently allow ref count
908 // calls to be nested (so that you can use this without having extra
909 // threads). Note 'drainCommands' is used so that these ref counts can't
910 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000911 if (exclusiveIncoming != nullptr) {
912 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000913 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000914 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000915 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
916 // prefer available socket, but if we don't have one, don't
917 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000918 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000919 }
920 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000921 }
922
Steven Moreland85e067b2021-05-26 17:43:53 +0000923 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000924 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000925 connection->mConnection = exclusive;
926 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000927 break;
928 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000929 connection->mConnection = available;
930 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000931 break;
932 }
933
Steven Morelanda59937e2021-10-04 17:42:30 -0700934 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000935 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
936 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
937 "reason: %d. Incoming connections: %zu. %s.",
938 static_cast<int>(use), session->mConnections.mIncoming.size(),
939 (session->server()
940 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
941 "for the corresponding client"
Steven Morelandfeb13e82023-03-01 01:25:33 +0000942 : "This is a client session, so see "
943 "RpcSession::setMaxOutgoingConnections "
Steven Moreland25d9cc52022-03-10 23:11:56 +0000944 "for this client or RpcServer::setMaxThreads for the corresponding "
945 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000946 return WOULD_BLOCK;
947 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000948
Steven Moreland85e067b2021-05-26 17:43:53 +0000949 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700950 session->mConnections.mOutgoing.size(),
951 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000952 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000953 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700954 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000955
956 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000957}
958
Andrei Homescue922b232022-04-23 03:41:09 +0000959void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000960 sp<RpcConnection>* available,
961 std::vector<sp<RpcConnection>>& sockets,
962 size_t socketsIndexHint) {
963 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
964 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
965
966 if (*exclusive != nullptr) return; // consistent with break below
967
968 for (size_t i = 0; i < sockets.size(); i++) {
969 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
970
Steven Moreland85e067b2021-05-26 17:43:53 +0000971 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000972 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
973 *available = socket;
974 continue;
975 }
976
Steven Moreland85e067b2021-05-26 17:43:53 +0000977 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000978 // (nested transactions)
979 if (exclusive && socket->exclusiveTid == tid) {
980 *exclusive = socket;
981 break; // consistent with return above
982 }
983 }
984}
985
986RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000987 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000988 // is using this fd, and it retains the right to it. So, we don't give up
989 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000990 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000991 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000992 }
993}
994
Pawan1c24f9c2022-08-26 23:23:15 +0000995bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
996 for (const auto& connection : connections) {
997 if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
998 return true;
999 }
1000 }
1001 return false;
1002}
1003
1004bool RpcSession::hasActiveRequests() {
1005 RpcMutexUniqueLock _l(mMutex);
1006 if (hasActiveConnection(mConnections.mIncoming)) {
1007 return true;
1008 }
1009 if (hasActiveConnection(mConnections.mOutgoing)) {
1010 return true;
1011 }
1012 return mConnections.mWaitingThreads != 0;
1013}
1014
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001015} // namespace android