blob: 7d6bcfc2a13eca9b26c88b590df6beb8955d7cd5 [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcSession"
18
19#include <binder/RpcSession.h>
20
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000023#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000024#include <unistd.h>
25
26#include <string_view>
27
Steven Moreland826367f2021-09-10 14:05:31 -070028#include <android-base/hex.h>
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 <android_runtime/vm.h>
50#include <jni.h>
51#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
Yifan Hong1f44f982021-10-08 17:16:47 -070093void RpcSession::setMaxOutgoingThreads(size_t threads) {
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");
Yifan Hong1f44f982021-10-08 17:16:47 -070097 mMaxOutgoingThreads = threads;
98}
99
100size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000101 RpcMutexLockGuard _l(mMutex);
Yifan Hong1f44f982021-10-08 17:16:47 -0700102 return mMaxOutgoingThreads;
103}
104
Andrei Homescu9b58a462022-07-28 02:26:46 +0000105bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
Steven Morelandbf57bce2021-07-26 15:26:12 -0700106 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
107 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
108 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
109 "is %u).",
110 version, RPC_WIRE_PROTOCOL_VERSION);
111 return false;
112 }
113
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000114 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000115 LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
116 "Must set protocol version before setting up connections");
Steven Moreland40b736e2021-07-30 14:37:10 -0700117 if (mProtocolVersion && version > *mProtocolVersion) {
118 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
119 *mProtocolVersion, version);
120 return false;
121 }
122
Steven Morelandbf57bce2021-07-26 15:26:12 -0700123 mProtocolVersion = version;
124 return true;
125}
126
Andrei Homescu9b58a462022-07-28 02:26:46 +0000127bool RpcSession::setProtocolVersion(uint32_t version) {
128 return setProtocolVersionInternal(version, true);
129}
130
Steven Morelandbf57bce2021-07-26 15:26:12 -0700131std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000132 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700133 return mProtocolVersion;
134}
135
Frederick Mayle69a0c992022-05-26 20:38:39 +0000136void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
Andrei Homescu9b58a462022-07-28 02:26:46 +0000137 RpcMutexLockGuard _l(mMutex);
138 LOG_ALWAYS_FATAL_IF(mStartedSetup,
139 "Must set file descriptor transport mode before setting up connections");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000140 mFileDescriptorTransportMode = mode;
141}
142
143RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
144 return mFileDescriptorTransportMode;
145}
146
Steven Moreland2372f9d2021-08-05 15:42:01 -0700147status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000148 return setupSocketClient(UnixSocketAddress(path));
149}
150
David Brazdil21c887c2022-09-23 12:25:18 +0100151status_t RpcSession::setupUnixDomainSocketBootstrapClient(unique_fd bootstrapFd) {
152 mBootstrapTransport =
153 mCtx->newTransport(RpcTransportFd(std::move(bootstrapFd)), mShutdownTrigger.get());
154 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
155 int socks[2];
156 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, socks) < 0) {
157 int savedErrno = errno;
158 ALOGE("Failed socketpair: %s", strerror(savedErrno));
159 return -savedErrno;
160 }
161 unique_fd clientFd(socks[0]), serverFd(socks[1]);
162
163 int zero = 0;
164 iovec iov{&zero, sizeof(zero)};
165 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
166 fds.push_back(std::move(serverFd));
167
168 status_t status = mBootstrapTransport->interruptableWriteFully(mShutdownTrigger.get(), &iov,
169 1, std::nullopt, &fds);
170 if (status != OK) {
171 ALOGE("Failed to send fd over bootstrap transport: %s", strerror(-status));
172 return status;
173 }
174
175 return initAndAddConnection(RpcTransportFd(std::move(clientFd)), sessionId, incoming);
176 });
177}
178
Steven Moreland2372f9d2021-08-05 15:42:01 -0700179status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 return setupSocketClient(VsockSocketAddress(cid, port));
181}
182
Steven Moreland2372f9d2021-08-05 15:42:01 -0700183status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700185 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
187 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700188 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189 }
190 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 -0700191 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192}
193
Pawan49d74cb2022-08-03 21:19:11 +0000194status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
195 std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000196 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700197 if (!fd.ok()) {
198 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700199 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700200 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700201 if (auto res = setNonBlocking(fd); !res.ok()) {
202 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
203 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
204 }
Pawan49d74cb2022-08-03 21:19:11 +0000205
Pawan3e0061c2022-08-26 21:08:34 +0000206 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000207 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000208 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
209 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700210 });
211}
212
Steven Moreland2372f9d2021-08-05 15:42:01 -0700213status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700214 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700215 if (auto status = initShutdownTrigger(); status != OK) return status;
216
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
218
219 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700220 int savedErrno = errno;
221 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
222 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 }
224
Pawan3e0061c2022-08-26 21:08:34 +0000225 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000226 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700227 if (server == nullptr) {
228 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700229 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700230 }
231 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000232}
233
234sp<IBinder> RpcSession::getRootObject() {
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 nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000239 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000240}
241
Steven Moreland1be91352021-05-11 22:12:15 +0000242status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000243 ExclusiveConnection connection;
244 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
245 ConnectionUse::CLIENT, &connection);
246 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000247 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000248}
249
Steven Morelandc9d7b532021-06-04 20:57:41 +0000250bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000251 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000252 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000253
254 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000255
Steven Morelandc9d7b532021-06-04 20:57:41 +0000256 if (wait) {
257 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700258 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700259
Steven Morelanda59937e2021-10-04 17:42:30 -0700260 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000261 }
262
263 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000264
Devin Moore66d5b7a2022-07-07 21:42:10 +0000265 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
266 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
267 statusToString(res).c_str());
268 }
269
Steven Moreland27a8bc72021-09-29 16:07:41 -0700270 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000271
Steven Moreland659416d2021-05-11 00:47:50 +0000272 return true;
273}
274
Steven Morelandf5174272021-05-25 00:39:28 +0000275status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000276 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000277 ExclusiveConnection connection;
278 status_t status =
279 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
280 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
281 : ConnectionUse::CLIENT,
282 &connection);
283 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000284 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285 sp<RpcSession>::fromExisting(this), reply, flags);
286}
287
Steven Moreland4f622fe2021-09-13 17:38:09 -0700288status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000289 // target is 0 because this is used to free BpBinder objects
290 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700291}
292
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000293status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000294 ExclusiveConnection connection;
295 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
296 ConnectionUse::CLIENT_REFCOUNT, &connection);
297 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000298 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
299 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300}
301
302status_t RpcSession::readId() {
303 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000304 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000305 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
306 }
307
Steven Moreland195edb82021-06-08 02:44:39 +0000308 ExclusiveConnection connection;
309 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
310 ConnectionUse::CLIENT, &connection);
311 if (status != OK) return status;
312
Steven Moreland826367f2021-09-10 14:05:31 -0700313 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314 if (status != OK) return status;
315
Steven Moreland826367f2021-09-10 14:05:31 -0700316 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
317 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000318 return OK;
319}
320
Steven Morelanddd67b942021-07-23 17:15:41 -0700321void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000322 const sp<RpcSession>& session) {
323 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000324}
325
Steven Moreland19fc9f72021-06-10 03:57:30 +0000326void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000327 mShutdownCount += 1;
Steven Moreland659416d2021-05-11 00:47:50 +0000328 mCv.notify_all();
329}
330
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000331void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700332 const sp<RpcSession>& session) {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000333 while (mShutdownCount < session->mConnections.mMaxIncoming) {
Steven Moreland659416d2021-05-11 00:47:50 +0000334 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700335 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
Steven Moreland8b7a7382022-10-08 04:00:54 +0000336 "still %zu/%zu fully shutdown.",
337 session->mConnections.mIncoming.size(), mShutdownCount.load(),
338 session->mConnections.mMaxIncoming);
Steven Moreland659416d2021-05-11 00:47:50 +0000339 }
340 }
341}
342
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000343void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
344 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345
Steven Morelanda63ff932021-05-12 00:03:15 +0000346 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000347 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700348 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000349 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000350}
Steven Morelanda63ff932021-05-12 00:03:15 +0000351
Yifan Hong702115c2021-06-24 15:39:18 -0700352RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
353 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000354 // must be registered to allow arbitrary client code executing commands to
355 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700356 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000357
Steven Morelanddd67b942021-07-23 17:15:41 -0700358 status_t status;
359
360 if (connection == nullptr) {
361 status = DEAD_OBJECT;
362 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700363 status =
364 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700365 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000366
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000367 return PreJoinSetupResult{
368 .connection = std::move(connection),
369 .status = status,
370 };
371}
372
Yifan Hong194acf22021-06-29 18:44:56 -0700373namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000374#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700375class JavaThreadAttacher {};
376#else
Yifan Hong194acf22021-06-29 18:44:56 -0700377// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
378// Android Runtime doesn't exist, no-op.
379class JavaThreadAttacher {
380public:
381 JavaThreadAttacher() {
382 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
383 // libbinder.
384 auto vm = getJavaVM();
385 if (vm == nullptr) return;
386
387 char threadName[16];
388 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
389 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
390 memcpy(threadName, defaultThreadName,
391 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
392 }
393 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
394 JavaVMAttachArgs args;
395 args.version = JNI_VERSION_1_2;
396 args.name = threadName;
397 args.group = nullptr;
398 JNIEnv* env;
399
400 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
401 "Cannot attach thread %s to JVM", threadName);
402 mAttached = true;
403 }
404 ~JavaThreadAttacher() {
405 if (!mAttached) return;
406 auto vm = getJavaVM();
407 LOG_ALWAYS_FATAL_IF(vm == nullptr,
408 "Unable to detach thread. No JavaVM, but it was present before!");
409
410 LOG_RPC_DETAIL("Detaching current thread from JVM");
411 if (vm->DetachCurrentThread() != JNI_OK) {
412 mAttached = false;
413 } else {
414 ALOGW("Unable to detach current thread from JVM");
415 }
416 }
417
418private:
419 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
420 bool mAttached = false;
421
422 static JavaVM* getJavaVM() {
423 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
424 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
425 if (fn == nullptr) return nullptr;
426 return fn();
427 }
428};
Yifan Hongd258e682021-11-01 18:34:42 -0700429#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700430} // namespace
431
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000432void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
433 sp<RpcConnection>& connection = setupResult.connection;
434
435 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700436 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700437 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000438 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000439 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000440 RpcState::CommandType::ANY);
441 if (status != OK) {
442 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
443 statusToString(status).c_str());
444 break;
445 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000447 } else {
448 ALOGE("Connection failed to init, closing with status %s",
449 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000450 }
451
Steven Moreland659416d2021-05-11 00:47:50 +0000452 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000453 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000454 RpcMutexLockGuard _l(session->mMutex);
455 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700456 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000457 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700458 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000459
Steven Moreland659416d2021-05-11 00:47:50 +0000460 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000461 }
462
Steven Morelanddd67b942021-07-23 17:15:41 -0700463 // done after all cleanup, since session shutdown progresses via callbacks here
464 if (connection != nullptr) {
465 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
466 "bad state: connection object guaranteed to be in list");
467 }
468
Steven Moreland659416d2021-05-11 00:47:50 +0000469 session = nullptr;
470
471 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000472 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000473 }
474}
475
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000476sp<RpcServer> RpcSession::server() {
477 RpcServer* unsafeServer = mForServer.unsafe_get();
478 sp<RpcServer> server = mForServer.promote();
479
480 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
481 "wp<> is to avoid strong cycle only");
482 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483}
484
Steven Moreland826367f2021-09-10 14:05:31 -0700485status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
486 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000488 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000489 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
490 mStartedSetup = true;
491
492 if constexpr (!kEnableRpcThreads) {
493 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
494 "Incoming threads are not supported on single-threaded libbinder");
495 // mMaxIncomingThreads should not change from here to its use below,
496 // since we set mStartedSetup==true and setMaxIncomingThreads checks
497 // for that
498 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700500
Yifan Hong832521e2021-08-05 14:55:40 -0700501 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000502
Steven Moreland27a8bc72021-09-29 16:07:41 -0700503 auto oldProtocolVersion = mProtocolVersion;
504 auto cleanup = base::ScopeGuard([&] {
505 // if any threads are started, shut them down
506 (void)shutdownAndWait(true);
507
508 mShutdownListener = nullptr;
509 mEventListener.clear();
510
511 mId.clear();
512
513 mShutdownTrigger = nullptr;
514 mRpcBinderState = std::make_unique<RpcState>();
515
516 // protocol version may have been downgraded - if we reuse this object
517 // to connect to another server, force that server to request a
518 // downgrade again
519 mProtocolVersion = oldProtocolVersion;
520
Steven Morelanda59937e2021-10-04 17:42:30 -0700521 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000522
523 // clear mStartedSetup so that we can reuse this RpcSession
524 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700525 });
526
Steven Moreland826367f2021-09-10 14:05:31 -0700527 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000528
Steven Morelandbf57bce2021-07-26 15:26:12 -0700529 {
530 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
532 ConnectionUse::CLIENT, &connection);
533 status != OK)
534 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700535
536 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700537 if (status_t status =
538 state()->readNewSessionResponse(connection.get(),
539 sp<RpcSession>::fromExisting(this), &version);
540 status != OK)
541 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000542 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700543 }
544
Steven Morelanda5036f02021-06-08 02:26:57 +0000545 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000547 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000548 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700549 ALOGE("Could not get max threads 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
554 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700555 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000556 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700557 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000558 }
559
Yifan Hong1f44f982021-10-08 17:16:47 -0700560 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
561 ALOGI_IF(outgoingThreads != numThreadsAvailable,
562 "Server hints client to start %zu outgoing threads, but client will only start %zu "
563 "because it is preconfigured to start at most %zu outgoing threads.",
564 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
565
Steven Morelanda5036f02021-06-08 02:26:57 +0000566 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000567 // instead of all at once - the other side should be responsible for setting
568 // up additional connections. We need to create at least one (unless 0 are
569 // requested to be set) in order to allow the other side to reliably make
570 // any requests at all.
571
Steven Moreland4198a122021-08-03 17:37:58 -0700572 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700573 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
574 "incoming threads",
575 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
576 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700577 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700578 }
579
Yifan Hong10423062021-10-08 16:26:32 -0700580 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700581 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000582 }
583
Steven Moreland27a8bc72021-09-29 16:07:41 -0700584 cleanup.Disable();
585
Steven Moreland2372f9d2021-08-05 15:42:01 -0700586 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000587}
588
Steven Moreland2372f9d2021-08-05 15:42:01 -0700589status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700590 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700591 return setupOneSocketConnection(addr, sessionId, incoming);
592 });
593}
594
Steven Moreland2372f9d2021-08-05 15:42:01 -0700595status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700596 const std::vector<uint8_t>& sessionId,
597 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000598 for (size_t tries = 0; tries < 5; tries++) {
599 if (tries > 0) usleep(10000);
600
Yifan Hongb675ffe2021-08-05 16:37:17 -0700601 unique_fd serverFd(TEMP_FAILURE_RETRY(
602 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000603 if (serverFd == -1) {
604 int savedErrno = errno;
605 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
606 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700607 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000608 }
609
Pawan3e0061c2022-08-26 21:08:34 +0000610 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000611
612 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700613 int connErrno = errno;
614 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
615 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
616 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Pawan49d74cb2022-08-03 21:19:11 +0000617 status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700618 if (pollStatus != OK) {
619 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
620 statusToString(pollStatus).c_str());
621 return pollStatus;
622 }
623 // Set connErrno to the errno that connect() would have set if the fd were blocking.
624 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000625 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
626 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700627 if (ret == -1) {
628 int savedErrno = errno;
629 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
630 "(Original error from connect() is: %s)",
631 strerror(savedErrno), strerror(connErrno));
632 return -savedErrno;
633 }
634 // Retrieved the real connErrno as if connect() was called with a blocking socket
635 // fd. Continue checking connErrno.
636 }
637 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000638 ALOGW("Connection reset on %s", addr.toString().c_str());
639 continue;
640 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700641 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
642 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700643 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700644 strerror(connErrno));
645 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700646 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000647 }
Pawan49d74cb2022-08-03 21:19:11 +0000648 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
649 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700650
Pawan49d74cb2022-08-03 21:19:11 +0000651 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000652 }
653
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000654 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700655 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000656}
657
Pawan3e0061c2022-08-26 21:08:34 +0000658status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700659 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700660 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700661 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700662 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700663 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700664 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700665 }
666
667 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
668
Steven Moreland826367f2021-09-10 14:05:31 -0700669 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
670 ALOGE("Session ID too big %zu", sessionId.size());
671 return BAD_VALUE;
672 }
673
Steven Moreland4198a122021-08-03 17:37:58 -0700674 RpcConnectionHeader header{
675 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
676 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000677 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700678 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700679 };
Steven Moreland4198a122021-08-03 17:37:58 -0700680
Steven Moreland826367f2021-09-10 14:05:31 -0700681 if (incoming) {
682 header.options |= RPC_CONNECTION_OPTION_INCOMING;
683 }
Steven Moreland4198a122021-08-03 17:37:58 -0700684
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000685 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000686 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
687 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700688 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700689 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700690 statusToString(sendHeaderStatus).c_str());
691 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700692 }
693
Steven Moreland826367f2021-09-10 14:05:31 -0700694 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000695 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
696 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000697 auto sendSessionIdStatus =
698 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
699 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700700 if (sendSessionIdStatus != OK) {
701 ALOGE("Could not write session ID ('%s') to socket: %s",
702 base::HexString(sessionId.data(), sessionId.size()).c_str(),
703 statusToString(sendSessionIdStatus).c_str());
704 return sendSessionIdStatus;
705 }
706 }
707
Steven Moreland4198a122021-08-03 17:37:58 -0700708 LOG_RPC_DETAIL("Socket at client: header sent");
709
710 if (incoming) {
711 return addIncomingConnection(std::move(server));
712 } else {
713 return addOutgoingConnection(std::move(server), true /*init*/);
714 }
715}
716
Steven Moreland2372f9d2021-08-05 15:42:01 -0700717status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000718 RpcMutex mutex;
719 RpcConditionVariable joinCv;
720 RpcMutexUniqueLock lock(mutex);
721 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000722 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
723 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000724 thread = RpcMaybeThread([&]() {
725 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700726 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000727 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
728 sp<RpcSession> session = thiz;
729 session->preJoinThreadOwnership(std::move(thread));
730
731 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700732 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000733
734 ownershipTransferred = true;
735 threadLock.unlock();
736 joinCv.notify_one();
737 // do not use & vars below
738
739 RpcSession::join(std::move(session), std::move(setupResult));
740 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000741 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000742 joinCv.wait(lock, [&] { return ownershipTransferred; });
743 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700744 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000745}
746
Yifan Hong832521e2021-08-05 14:55:40 -0700747status_t RpcSession::initShutdownTrigger() {
748 // first client connection added, but setForServer not called, so
749 // initializaing for a client.
750 if (mShutdownTrigger == nullptr) {
751 mShutdownTrigger = FdTrigger::make();
752 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
753 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
754 }
755 return OK;
756}
757
Steven Moreland2372f9d2021-08-05 15:42:01 -0700758status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000759 sp<RpcConnection> connection = sp<RpcConnection>::make();
760 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000761 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700762 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000763 connection->exclusiveTid = rpcGetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700764 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000765 }
766
Steven Morelandb86e26b2021-06-12 00:35:58 +0000767 status_t status = OK;
768 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700769 status =
770 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000771 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000772
Andrei Homescuc8490872022-06-23 05:18:51 +0000773 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000774
Steven Moreland2372f9d2021-08-05 15:42:01 -0700775 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000776}
777
Steven Morelanda8b44292021-06-08 01:27:53 +0000778bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700779 const std::vector<uint8_t>& sessionId,
780 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000781 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
782 LOG_ALWAYS_FATAL_IF(server == nullptr);
783 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
784 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000785 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000786 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000787
788 mShutdownTrigger = FdTrigger::make();
789 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000790
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000791 mId = sessionId;
792 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000793 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700794 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000795 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000796}
797
Yifan Hong702115c2021-06-24 15:39:18 -0700798sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
799 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000800 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700801
Yifan Hong10423062021-10-08 16:26:32 -0700802 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700803 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700804 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700805 return nullptr;
806 }
807
Steven Morelanddd67b942021-07-23 17:15:41 -0700808 // Don't accept any more connections, some have shutdown. Usually this
809 // happens when new connections are still being established as part of a
810 // very short-lived session which shuts down after it already started
811 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700812 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700813 return nullptr;
814 }
815
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000816 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700817 session->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000818 session->exclusiveTid = rpcGetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700819
Steven Morelanda59937e2021-10-04 17:42:30 -0700820 mConnections.mIncoming.push_back(session);
821 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000822
823 return session;
824}
825
Steven Moreland19fc9f72021-06-10 03:57:30 +0000826bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000827 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700828 if (auto it =
829 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
830 it != mConnections.mIncoming.end()) {
831 mConnections.mIncoming.erase(it);
832 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000833 sp<EventListener> listener = mEventListener.promote();
834 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700835 _l.unlock();
836 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000837 }
Steven Morelandee78e762021-05-05 21:12:51 +0000838 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000839 return true;
840 }
841 return false;
842}
843
Andrei Homescuc8490872022-06-23 05:18:51 +0000844void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000845 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000846 connection->exclusiveTid = std::nullopt;
847 if (mConnections.mWaitingThreads > 0) {
848 _l.unlock();
849 mAvailableConnectionCv.notify_one();
850 }
851}
852
Yifan Hong9734cfc2021-09-13 16:14:09 -0700853std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700854 return mCtx->getCertificate(format);
855}
856
Steven Moreland195edb82021-06-08 02:44:39 +0000857status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
858 ExclusiveConnection* connection) {
859 connection->mSession = session;
860 connection->mConnection = nullptr;
861 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000862
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000863 uint64_t tid = rpcGetThreadId();
864 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000865
Steven Morelanda59937e2021-10-04 17:42:30 -0700866 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000867 while (true) {
868 sp<RpcConnection> exclusive;
869 sp<RpcConnection> available;
870
871 // CHECK FOR DEDICATED CLIENT SOCKET
872 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000873 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700874 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
875 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000876
877 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700878 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000879 //
880 // Imagine we have more than one thread in play, and a single thread
881 // sends a synchronous, then an asynchronous command. Imagine the
882 // asynchronous command is sent on the first client connection. Then, if
883 // we naively send a synchronous command to that same connection, the
884 // thread on the far side might be busy processing the asynchronous
885 // command. So, we move to considering the second available thread
886 // for subsequent calls.
887 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700888 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
889 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000890 }
891
Steven Morelandc7d40132021-06-10 03:42:11 +0000892 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000893 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000894 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000895 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000896 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700897 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000898
899 // asynchronous calls cannot be nested, we currently allow ref count
900 // calls to be nested (so that you can use this without having extra
901 // threads). Note 'drainCommands' is used so that these ref counts can't
902 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000903 if (exclusiveIncoming != nullptr) {
904 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000905 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000906 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000907 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
908 // prefer available socket, but if we don't have one, don't
909 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000910 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000911 }
912 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000913 }
914
Steven Moreland85e067b2021-05-26 17:43:53 +0000915 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000916 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000917 connection->mConnection = exclusive;
918 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000919 break;
920 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000921 connection->mConnection = available;
922 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000923 break;
924 }
925
Steven Morelanda59937e2021-10-04 17:42:30 -0700926 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000927 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
928 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
929 "reason: %d. Incoming connections: %zu. %s.",
930 static_cast<int>(use), session->mConnections.mIncoming.size(),
931 (session->server()
932 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
933 "for the corresponding client"
934 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
935 "for this client or RpcServer::setMaxThreads for the corresponding "
936 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000937 return WOULD_BLOCK;
938 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000939
Steven Moreland85e067b2021-05-26 17:43:53 +0000940 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700941 session->mConnections.mOutgoing.size(),
942 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000943 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000944 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700945 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000946
947 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000948}
949
Andrei Homescue922b232022-04-23 03:41:09 +0000950void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000951 sp<RpcConnection>* available,
952 std::vector<sp<RpcConnection>>& sockets,
953 size_t socketsIndexHint) {
954 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
955 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
956
957 if (*exclusive != nullptr) return; // consistent with break below
958
959 for (size_t i = 0; i < sockets.size(); i++) {
960 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
961
Steven Moreland85e067b2021-05-26 17:43:53 +0000962 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000963 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
964 *available = socket;
965 continue;
966 }
967
Steven Moreland85e067b2021-05-26 17:43:53 +0000968 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000969 // (nested transactions)
970 if (exclusive && socket->exclusiveTid == tid) {
971 *exclusive = socket;
972 break; // consistent with return above
973 }
974 }
975}
976
977RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000978 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000979 // is using this fd, and it retains the right to it. So, we don't give up
980 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000981 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000982 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000983 }
984}
985
Pawan1c24f9c2022-08-26 23:23:15 +0000986bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
987 for (const auto& connection : connections) {
988 if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
989 return true;
990 }
991 }
992 return false;
993}
994
995bool RpcSession::hasActiveRequests() {
996 RpcMutexUniqueLock _l(mMutex);
997 if (hasActiveConnection(mConnections.mIncoming)) {
998 return true;
999 }
1000 if (hasActiveConnection(mConnections.mOutgoing)) {
1001 return true;
1002 }
1003 return mConnections.mWaitingThreads != 0;
1004}
1005
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001006} // namespace android