blob: 70382c072201389a09efcbfe5be5baf1dcff278c [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
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +000029#include <android-base/scopeguard.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070030#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000032#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070033#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/Stability.h>
35#include <utils/String8.h>
36
Andrei Homescu9b58a462022-07-28 02:26:46 +000037#include "BuildFlags.h"
Yifan Hong8c950422021-08-05 17:13:55 -070038#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000039#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000040#include "RpcSocketAddress.h"
41#include "RpcState.h"
David Brazdil21c887c2022-09-23 12:25:18 +010042#include "RpcTransportUtils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000043#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070044#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000046#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070047#include <jni.h>
Jeongik Cha0c47d452022-10-20 00:07:55 +090048extern "C" JavaVM* AndroidRuntimeGetJavaVM();
Yifan Hongd258e682021-11-01 18:34:42 -070049#endif
50
Steven Morelandbdb53ab2021-05-05 17:57:41 +000051namespace android {
52
53using base::unique_fd;
54
Yifan Hongecf937d2021-08-11 17:29:28 -070055RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056 LOG_RPC_DETAIL("RpcSession created %p", this);
57
Steven Moreland27a8bc72021-09-29 16:07:41 -070058 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059}
60RpcSession::~RpcSession() {
61 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
62
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000063 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070064 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000065 "Should not be able to destroy a session with servers in use.");
66}
67
Yifan Hongecf937d2021-08-11 17:29:28 -070068sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070069 // Default is without TLS.
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +000070 return make(binder::os::makeDefaultRpcTransportCtxFactory());
Yifan Hongecf937d2021-08-11 17:29:28 -070071}
72
Yifan Hongfdd9f692021-09-09 15:12:52 -070073sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070074 auto ctx = rpcTransportCtxFactory->newClientCtx();
75 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070076 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077}
78
Yifan Hong10423062021-10-08 16:26:32 -070079void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000080 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000081 LOG_ALWAYS_FATAL_IF(mStartedSetup,
82 "Must set max incoming threads before setting up connections");
Yifan Hong10423062021-10-08 16:26:32 -070083 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000084}
85
Yifan Hong10423062021-10-08 16:26:32 -070086size_t RpcSession::getMaxIncomingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000087 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070088 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000089}
90
Steven Morelande65f73c2023-03-04 01:34:50 +000091void RpcSession::setMaxOutgoingConnections(size_t connections) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000092 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000093 LOG_ALWAYS_FATAL_IF(mStartedSetup,
94 "Must set max outgoing threads before setting up connections");
Steven Morelande65f73c2023-03-04 01:34:50 +000095 mMaxOutgoingConnections = connections;
Yifan Hong1f44f982021-10-08 17:16:47 -070096}
97
98size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000099 RpcMutexLockGuard _l(mMutex);
Steven Morelande65f73c2023-03-04 01:34:50 +0000100 return mMaxOutgoingConnections;
Yifan Hong1f44f982021-10-08 17:16:47 -0700101}
102
Andrei Homescu9b58a462022-07-28 02:26:46 +0000103bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000104 if (!RpcState::validateProtocolVersion(version)) {
Steven Morelandbf57bce2021-07-26 15:26:12 -0700105 return false;
106 }
107
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000108 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000109 LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
110 "Must set protocol version before setting up connections");
Steven Moreland40b736e2021-07-30 14:37:10 -0700111 if (mProtocolVersion && version > *mProtocolVersion) {
112 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
113 *mProtocolVersion, version);
114 return false;
115 }
116
Steven Morelandbf57bce2021-07-26 15:26:12 -0700117 mProtocolVersion = version;
118 return true;
119}
120
Andrei Homescu9b58a462022-07-28 02:26:46 +0000121bool RpcSession::setProtocolVersion(uint32_t version) {
122 return setProtocolVersionInternal(version, true);
123}
124
Steven Morelandbf57bce2021-07-26 15:26:12 -0700125std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000126 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700127 return mProtocolVersion;
128}
129
Frederick Mayle69a0c992022-05-26 20:38:39 +0000130void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
Andrei Homescu9b58a462022-07-28 02:26:46 +0000131 RpcMutexLockGuard _l(mMutex);
132 LOG_ALWAYS_FATAL_IF(mStartedSetup,
133 "Must set file descriptor transport mode before setting up connections");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000134 mFileDescriptorTransportMode = mode;
135}
136
137RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
138 return mFileDescriptorTransportMode;
139}
140
Steven Moreland2372f9d2021-08-05 15:42:01 -0700141status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000142 return setupSocketClient(UnixSocketAddress(path));
143}
144
David Brazdil21c887c2022-09-23 12:25:18 +0100145status_t RpcSession::setupUnixDomainSocketBootstrapClient(unique_fd bootstrapFd) {
146 mBootstrapTransport =
147 mCtx->newTransport(RpcTransportFd(std::move(bootstrapFd)), mShutdownTrigger.get());
148 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
149 int socks[2];
150 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, socks) < 0) {
151 int savedErrno = errno;
152 ALOGE("Failed socketpair: %s", strerror(savedErrno));
153 return -savedErrno;
154 }
155 unique_fd clientFd(socks[0]), serverFd(socks[1]);
156
157 int zero = 0;
158 iovec iov{&zero, sizeof(zero)};
159 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
160 fds.push_back(std::move(serverFd));
161
162 status_t status = mBootstrapTransport->interruptableWriteFully(mShutdownTrigger.get(), &iov,
163 1, std::nullopt, &fds);
164 if (status != OK) {
165 ALOGE("Failed to send fd over bootstrap transport: %s", strerror(-status));
166 return status;
167 }
168
169 return initAndAddConnection(RpcTransportFd(std::move(clientFd)), sessionId, incoming);
170 });
171}
172
Steven Moreland2372f9d2021-08-05 15:42:01 -0700173status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 return setupSocketClient(VsockSocketAddress(cid, port));
175}
176
Steven Moreland2372f9d2021-08-05 15:42:01 -0700177status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700179 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
181 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700182 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183 }
184 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 -0700185 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186}
187
Pawan49d74cb2022-08-03 21:19:11 +0000188status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
189 std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000190 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700191 if (!fd.ok()) {
192 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700193 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700194 }
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700195 if (status_t res = binder::os::setNonBlocking(fd); res != OK) return res;
Pawan49d74cb2022-08-03 21:19:11 +0000196
Pawan3e0061c2022-08-26 21:08:34 +0000197 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000198 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000199 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
200 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700201 });
202}
203
Steven Moreland2372f9d2021-08-05 15:42:01 -0700204status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700205 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700206 if (auto status = initShutdownTrigger(); status != OK) return status;
207
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000208 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
209
210 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700211 int savedErrno = errno;
212 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
213 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000214 }
215
Pawan3e0061c2022-08-26 21:08:34 +0000216 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000217 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700218 if (server == nullptr) {
219 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700220 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700221 }
222 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223}
224
225sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000226 ExclusiveConnection connection;
227 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
228 ConnectionUse::CLIENT, &connection);
229 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000230 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000231}
232
Steven Moreland1be91352021-05-11 22:12:15 +0000233status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000234 ExclusiveConnection connection;
235 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
236 ConnectionUse::CLIENT, &connection);
237 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000238 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239}
240
Steven Morelandc9d7b532021-06-04 20:57:41 +0000241bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000242 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000243 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000244
245 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000246
Steven Morelandc9d7b532021-06-04 20:57:41 +0000247 if (wait) {
248 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700249 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700250
Steven Morelanda59937e2021-10-04 17:42:30 -0700251 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000252 }
253
254 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000255
Devin Moore66d5b7a2022-07-07 21:42:10 +0000256 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
257 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
258 statusToString(res).c_str());
259 }
260
Steven Moreland27a8bc72021-09-29 16:07:41 -0700261 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000262
Steven Moreland659416d2021-05-11 00:47:50 +0000263 return true;
264}
265
Steven Morelandf5174272021-05-25 00:39:28 +0000266status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000268 ExclusiveConnection connection;
269 status_t status =
270 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
271 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
272 : ConnectionUse::CLIENT,
273 &connection);
274 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000275 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000276 sp<RpcSession>::fromExisting(this), reply, flags);
277}
278
Steven Moreland4f622fe2021-09-13 17:38:09 -0700279status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000280 // target is 0 because this is used to free BpBinder objects
281 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700282}
283
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000284status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000285 ExclusiveConnection connection;
286 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
287 ConnectionUse::CLIENT_REFCOUNT, &connection);
288 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000289 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
290 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291}
292
293status_t RpcSession::readId() {
294 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000295 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
297 }
298
Steven Moreland195edb82021-06-08 02:44:39 +0000299 ExclusiveConnection connection;
300 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
301 ConnectionUse::CLIENT, &connection);
302 if (status != OK) return status;
303
Steven Moreland826367f2021-09-10 14:05:31 -0700304 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000305 if (status != OK) return status;
306
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000307 LOG_RPC_DETAIL("RpcSession %p has id %s", this, HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000308 return OK;
309}
310
Steven Morelanddd67b942021-07-23 17:15:41 -0700311void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000312 const sp<RpcSession>& session) {
313 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000314}
315
Steven Moreland19fc9f72021-06-10 03:57:30 +0000316void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000317 mShutdownCount += 1;
Steven Moreland659416d2021-05-11 00:47:50 +0000318 mCv.notify_all();
319}
320
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000321void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700322 const sp<RpcSession>& session) {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000323 while (mShutdownCount < session->mConnections.mMaxIncoming) {
Steven Moreland659416d2021-05-11 00:47:50 +0000324 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700325 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
Steven Moreland8b7a7382022-10-08 04:00:54 +0000326 "still %zu/%zu fully shutdown.",
327 session->mConnections.mIncoming.size(), mShutdownCount.load(),
328 session->mConnections.mMaxIncoming);
Steven Moreland659416d2021-05-11 00:47:50 +0000329 }
330 }
331}
332
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000333void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
334 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335
Steven Morelanda63ff932021-05-12 00:03:15 +0000336 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000337 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700338 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000339 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000340}
Steven Morelanda63ff932021-05-12 00:03:15 +0000341
Yifan Hong702115c2021-06-24 15:39:18 -0700342RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
343 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000344 // must be registered to allow arbitrary client code executing commands to
345 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700346 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000347
Steven Morelanddd67b942021-07-23 17:15:41 -0700348 status_t status;
349
350 if (connection == nullptr) {
351 status = DEAD_OBJECT;
352 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700353 status =
354 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700355 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000356
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000357 return PreJoinSetupResult{
358 .connection = std::move(connection),
359 .status = status,
360 };
361}
362
Yifan Hong194acf22021-06-29 18:44:56 -0700363namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000364#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700365class JavaThreadAttacher {};
366#else
Yifan Hong194acf22021-06-29 18:44:56 -0700367// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
368// Android Runtime doesn't exist, no-op.
369class JavaThreadAttacher {
370public:
371 JavaThreadAttacher() {
372 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
373 // libbinder.
374 auto vm = getJavaVM();
375 if (vm == nullptr) return;
376
377 char threadName[16];
378 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
379 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
380 memcpy(threadName, defaultThreadName,
381 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
382 }
383 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
384 JavaVMAttachArgs args;
385 args.version = JNI_VERSION_1_2;
386 args.name = threadName;
387 args.group = nullptr;
388 JNIEnv* env;
389
390 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
391 "Cannot attach thread %s to JVM", threadName);
392 mAttached = true;
393 }
394 ~JavaThreadAttacher() {
395 if (!mAttached) return;
396 auto vm = getJavaVM();
397 LOG_ALWAYS_FATAL_IF(vm == nullptr,
398 "Unable to detach thread. No JavaVM, but it was present before!");
399
400 LOG_RPC_DETAIL("Detaching current thread from JVM");
Steven Morelandd0c9a172022-10-24 15:46:21 +0000401 int ret = vm->DetachCurrentThread();
402 if (ret == JNI_OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700403 mAttached = false;
404 } else {
Steven Morelandd0c9a172022-10-24 15:46:21 +0000405 ALOGW("Unable to detach current thread from JVM (%d)", ret);
Yifan Hong194acf22021-06-29 18:44:56 -0700406 }
407 }
408
409private:
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700410 JavaThreadAttacher(const JavaThreadAttacher&) = delete;
411 void operator=(const JavaThreadAttacher&) = delete;
412
Yifan Hong194acf22021-06-29 18:44:56 -0700413 bool mAttached = false;
414
415 static JavaVM* getJavaVM() {
416 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
417 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
418 if (fn == nullptr) return nullptr;
419 return fn();
420 }
421};
Yifan Hongd258e682021-11-01 18:34:42 -0700422#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700423} // namespace
424
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000425void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
426 sp<RpcConnection>& connection = setupResult.connection;
427
428 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700429 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700430 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000431 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000432 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000433 RpcState::CommandType::ANY);
434 if (status != OK) {
435 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
436 statusToString(status).c_str());
437 break;
438 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000440 } else {
441 ALOGE("Connection failed to init, closing with status %s",
442 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000443 }
444
Steven Moreland659416d2021-05-11 00:47:50 +0000445 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000446 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000447 RpcMutexLockGuard _l(session->mMutex);
448 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700449 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000450 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700451 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000452
Steven Moreland659416d2021-05-11 00:47:50 +0000453 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000454 }
455
Steven Morelanddd67b942021-07-23 17:15:41 -0700456 // done after all cleanup, since session shutdown progresses via callbacks here
457 if (connection != nullptr) {
458 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
459 "bad state: connection object guaranteed to be in list");
460 }
461
Steven Moreland659416d2021-05-11 00:47:50 +0000462 session = nullptr;
463
464 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000465 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000466 }
467}
468
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000469sp<RpcServer> RpcSession::server() {
470 RpcServer* unsafeServer = mForServer.unsafe_get();
471 sp<RpcServer> server = mForServer.promote();
472
473 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
474 "wp<> is to avoid strong cycle only");
475 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000476}
477
Steven Moreland826367f2021-09-10 14:05:31 -0700478status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
479 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000481 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000482 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
483 mStartedSetup = true;
484
485 if constexpr (!kEnableRpcThreads) {
486 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
487 "Incoming threads are not supported on single-threaded libbinder");
488 // mMaxIncomingThreads should not change from here to its use below,
489 // since we set mStartedSetup==true and setMaxIncomingThreads checks
490 // for that
491 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000492 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700493
Yifan Hong832521e2021-08-05 14:55:40 -0700494 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495
Steven Moreland27a8bc72021-09-29 16:07:41 -0700496 auto oldProtocolVersion = mProtocolVersion;
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +0000497 auto cleanup = base::ScopeGuard([&] {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700498 // if any threads are started, shut them down
499 (void)shutdownAndWait(true);
500
501 mShutdownListener = nullptr;
502 mEventListener.clear();
503
504 mId.clear();
505
506 mShutdownTrigger = nullptr;
507 mRpcBinderState = std::make_unique<RpcState>();
508
509 // protocol version may have been downgraded - if we reuse this object
510 // to connect to another server, force that server to request a
511 // downgrade again
512 mProtocolVersion = oldProtocolVersion;
513
Steven Morelanda59937e2021-10-04 17:42:30 -0700514 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000515
516 // clear mStartedSetup so that we can reuse this RpcSession
517 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700518 });
519
Steven Moreland826367f2021-09-10 14:05:31 -0700520 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521
Steven Morelandbf57bce2021-07-26 15:26:12 -0700522 {
523 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700524 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
525 ConnectionUse::CLIENT, &connection);
526 status != OK)
527 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700528
529 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700530 if (status_t status =
531 state()->readNewSessionResponse(connection.get(),
532 sp<RpcSession>::fromExisting(this), &version);
533 status != OK)
534 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000535 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700536 }
537
Steven Morelanda5036f02021-06-08 02:26:57 +0000538 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000539 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000541 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700542 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700544 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000545 }
546
547 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700548 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000549 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000551 }
552
Steven Morelande65f73c2023-03-04 01:34:50 +0000553 size_t outgoingConnections = std::min(numThreadsAvailable, mMaxOutgoingConnections);
554 ALOGI_IF(outgoingConnections != numThreadsAvailable,
Yifan Hong1f44f982021-10-08 17:16:47 -0700555 "Server hints client to start %zu outgoing threads, but client will only start %zu "
556 "because it is preconfigured to start at most %zu outgoing threads.",
Steven Morelande65f73c2023-03-04 01:34:50 +0000557 numThreadsAvailable, outgoingConnections, mMaxOutgoingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700558
Steven Morelanda5036f02021-06-08 02:26:57 +0000559 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000560 // instead of all at once - the other side should be responsible for setting
561 // up additional connections. We need to create at least one (unless 0 are
562 // requested to be set) in order to allow the other side to reliably make
563 // any requests at all.
564
Steven Moreland4198a122021-08-03 17:37:58 -0700565 // we've already setup one client
Steven Morelande65f73c2023-03-04 01:34:50 +0000566 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing connections (server max: "
567 "%zu) and %zu incoming threads",
568 outgoingConnections, numThreadsAvailable, mMaxIncomingThreads);
569 for (size_t i = 0; i + 1 < outgoingConnections; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700570 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700571 }
572
Yifan Hong10423062021-10-08 16:26:32 -0700573 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700574 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000575 }
576
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +0000577 cleanup.Disable();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700578
Steven Moreland2372f9d2021-08-05 15:42:01 -0700579 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000580}
581
Steven Moreland2372f9d2021-08-05 15:42:01 -0700582status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700583 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700584 return setupOneSocketConnection(addr, sessionId, incoming);
585 });
586}
587
Steven Moreland2372f9d2021-08-05 15:42:01 -0700588status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700589 const std::vector<uint8_t>& sessionId,
590 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000591 for (size_t tries = 0; tries < 5; tries++) {
592 if (tries > 0) usleep(10000);
593
Yifan Hongb675ffe2021-08-05 16:37:17 -0700594 unique_fd serverFd(TEMP_FAILURE_RETRY(
595 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000596 if (serverFd == -1) {
597 int savedErrno = errno;
598 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
599 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700600 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000601 }
602
Steven Moreland12af6f72023-03-07 15:14:25 +0000603 if (addr.addr()->sa_family == AF_INET || addr.addr()->sa_family == AF_INET6) {
604 int noDelay = 1;
605 int result =
606 setsockopt(serverFd.get(), IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay));
607 if (result < 0) {
608 int savedErrno = errno;
609 ALOGE("Could not set TCP_NODELAY on %s: %s", addr.toString().c_str(),
610 strerror(savedErrno));
611 return -savedErrno;
612 }
613 }
614
Pawan3e0061c2022-08-26 21:08:34 +0000615 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000616
617 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700618 int connErrno = errno;
619 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
620 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
621 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Pawan49d74cb2022-08-03 21:19:11 +0000622 status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700623 if (pollStatus != OK) {
624 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
625 statusToString(pollStatus).c_str());
626 return pollStatus;
627 }
628 // Set connErrno to the errno that connect() would have set if the fd were blocking.
629 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000630 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
631 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700632 if (ret == -1) {
633 int savedErrno = errno;
634 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
635 "(Original error from connect() is: %s)",
636 strerror(savedErrno), strerror(connErrno));
637 return -savedErrno;
638 }
639 // Retrieved the real connErrno as if connect() was called with a blocking socket
640 // fd. Continue checking connErrno.
641 }
642 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000643 ALOGW("Connection reset on %s", addr.toString().c_str());
644 continue;
645 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700646 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
647 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700648 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700649 strerror(connErrno));
650 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700651 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000652 }
Pawan49d74cb2022-08-03 21:19:11 +0000653 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
654 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700655
Pawan49d74cb2022-08-03 21:19:11 +0000656 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000657 }
658
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000659 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700660 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000661}
662
Pawan3e0061c2022-08-26 21:08:34 +0000663status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700664 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700665 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700666 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700667 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700668 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700669 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700670 }
671
672 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
673
Steven Moreland826367f2021-09-10 14:05:31 -0700674 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
675 ALOGE("Session ID too big %zu", sessionId.size());
676 return BAD_VALUE;
677 }
678
Steven Moreland4198a122021-08-03 17:37:58 -0700679 RpcConnectionHeader header{
680 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
681 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000682 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700683 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700684 };
Steven Moreland4198a122021-08-03 17:37:58 -0700685
Steven Moreland826367f2021-09-10 14:05:31 -0700686 if (incoming) {
687 header.options |= RPC_CONNECTION_OPTION_INCOMING;
688 }
Steven Moreland4198a122021-08-03 17:37:58 -0700689
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000690 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000691 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
692 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700693 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700694 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700695 statusToString(sendHeaderStatus).c_str());
696 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700697 }
698
Steven Moreland826367f2021-09-10 14:05:31 -0700699 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000700 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
701 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000702 auto sendSessionIdStatus =
703 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
704 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700705 if (sendSessionIdStatus != OK) {
706 ALOGE("Could not write session ID ('%s') to socket: %s",
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000707 HexString(sessionId.data(), sessionId.size()).c_str(),
Steven Moreland826367f2021-09-10 14:05:31 -0700708 statusToString(sendSessionIdStatus).c_str());
709 return sendSessionIdStatus;
710 }
711 }
712
Steven Moreland4198a122021-08-03 17:37:58 -0700713 LOG_RPC_DETAIL("Socket at client: header sent");
714
715 if (incoming) {
716 return addIncomingConnection(std::move(server));
717 } else {
718 return addOutgoingConnection(std::move(server), true /*init*/);
719 }
720}
721
Steven Moreland2372f9d2021-08-05 15:42:01 -0700722status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000723 RpcMutex mutex;
724 RpcConditionVariable joinCv;
725 RpcMutexUniqueLock lock(mutex);
726 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000727 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
728 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000729 thread = RpcMaybeThread([&]() {
730 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700731 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000732 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
733 sp<RpcSession> session = thiz;
734 session->preJoinThreadOwnership(std::move(thread));
735
736 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700737 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000738
739 ownershipTransferred = true;
740 threadLock.unlock();
741 joinCv.notify_one();
742 // do not use & vars below
743
744 RpcSession::join(std::move(session), std::move(setupResult));
745 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000746 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000747 joinCv.wait(lock, [&] { return ownershipTransferred; });
748 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700749 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000750}
751
Yifan Hong832521e2021-08-05 14:55:40 -0700752status_t RpcSession::initShutdownTrigger() {
753 // first client connection added, but setForServer not called, so
754 // initializaing for a client.
755 if (mShutdownTrigger == nullptr) {
756 mShutdownTrigger = FdTrigger::make();
757 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
758 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
759 }
760 return OK;
761}
762
Steven Moreland2372f9d2021-08-05 15:42:01 -0700763status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000764 sp<RpcConnection> connection = sp<RpcConnection>::make();
765 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000766 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700767 connection->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000768 connection->exclusiveTid = binder::os::GetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700769 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000770 }
771
Steven Morelandb86e26b2021-06-12 00:35:58 +0000772 status_t status = OK;
773 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700774 status =
775 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000776 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000777
Andrei Homescuc8490872022-06-23 05:18:51 +0000778 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000779
Steven Moreland2372f9d2021-08-05 15:42:01 -0700780 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000781}
782
Steven Morelanda8b44292021-06-08 01:27:53 +0000783bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700784 const std::vector<uint8_t>& sessionId,
785 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000786 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
787 LOG_ALWAYS_FATAL_IF(server == nullptr);
788 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
789 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000790 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000791 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000792
793 mShutdownTrigger = FdTrigger::make();
794 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000795
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000796 mId = sessionId;
797 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000798 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700799 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000800 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000801}
802
Yifan Hong702115c2021-06-24 15:39:18 -0700803sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
804 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000805 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700806
Yifan Hong10423062021-10-08 16:26:32 -0700807 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700808 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700809 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700810 return nullptr;
811 }
812
Steven Morelanddd67b942021-07-23 17:15:41 -0700813 // Don't accept any more connections, some have shutdown. Usually this
814 // happens when new connections are still being established as part of a
815 // very short-lived session which shuts down after it already started
816 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700817 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700818 return nullptr;
819 }
820
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000821 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700822 session->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000823 session->exclusiveTid = binder::os::GetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700824
Steven Morelanda59937e2021-10-04 17:42:30 -0700825 mConnections.mIncoming.push_back(session);
826 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000827
828 return session;
829}
830
Steven Moreland19fc9f72021-06-10 03:57:30 +0000831bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000832 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700833 if (auto it =
834 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
835 it != mConnections.mIncoming.end()) {
836 mConnections.mIncoming.erase(it);
837 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000838 sp<EventListener> listener = mEventListener.promote();
839 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700840 _l.unlock();
841 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000842 }
Steven Morelandee78e762021-05-05 21:12:51 +0000843 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000844 return true;
845 }
846 return false;
847}
848
Andrei Homescuc8490872022-06-23 05:18:51 +0000849void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000850 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000851 connection->exclusiveTid = std::nullopt;
852 if (mConnections.mWaitingThreads > 0) {
853 _l.unlock();
854 mAvailableConnectionCv.notify_one();
855 }
856}
857
Yifan Hong9734cfc2021-09-13 16:14:09 -0700858std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700859 return mCtx->getCertificate(format);
860}
861
Steven Moreland195edb82021-06-08 02:44:39 +0000862status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
863 ExclusiveConnection* connection) {
864 connection->mSession = session;
865 connection->mConnection = nullptr;
866 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000867
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000868 uint64_t tid = binder::os::GetThreadId();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000869 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000870
Steven Morelanda59937e2021-10-04 17:42:30 -0700871 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000872 while (true) {
873 sp<RpcConnection> exclusive;
874 sp<RpcConnection> available;
875
876 // CHECK FOR DEDICATED CLIENT SOCKET
877 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000878 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700879 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
880 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000881
882 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700883 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000884 //
885 // Imagine we have more than one thread in play, and a single thread
886 // sends a synchronous, then an asynchronous command. Imagine the
887 // asynchronous command is sent on the first client connection. Then, if
888 // we naively send a synchronous command to that same connection, the
889 // thread on the far side might be busy processing the asynchronous
890 // command. So, we move to considering the second available thread
891 // for subsequent calls.
892 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700893 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
894 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000895 }
896
Steven Morelandc7d40132021-06-10 03:42:11 +0000897 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000898 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000899 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000900 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000901 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700902 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000903
904 // asynchronous calls cannot be nested, we currently allow ref count
905 // calls to be nested (so that you can use this without having extra
906 // threads). Note 'drainCommands' is used so that these ref counts can't
907 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000908 if (exclusiveIncoming != nullptr) {
909 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000910 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000911 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000912 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
913 // prefer available socket, but if we don't have one, don't
914 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000915 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000916 }
917 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000918 }
919
Steven Moreland85e067b2021-05-26 17:43:53 +0000920 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000921 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000922 connection->mConnection = exclusive;
923 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000924 break;
925 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000926 connection->mConnection = available;
927 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000928 break;
929 }
930
Steven Morelanda59937e2021-10-04 17:42:30 -0700931 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000932 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
933 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
934 "reason: %d. Incoming connections: %zu. %s.",
935 static_cast<int>(use), session->mConnections.mIncoming.size(),
936 (session->server()
937 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
938 "for the corresponding client"
Steven Morelandfeb13e82023-03-01 01:25:33 +0000939 : "This is a client session, so see "
940 "RpcSession::setMaxOutgoingConnections "
Steven Moreland25d9cc52022-03-10 23:11:56 +0000941 "for this client or RpcServer::setMaxThreads for the corresponding "
942 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000943 return WOULD_BLOCK;
944 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000945
Steven Moreland85e067b2021-05-26 17:43:53 +0000946 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700947 session->mConnections.mOutgoing.size(),
948 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000949 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000950 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700951 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000952
953 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000954}
955
Andrei Homescue922b232022-04-23 03:41:09 +0000956void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000957 sp<RpcConnection>* available,
958 std::vector<sp<RpcConnection>>& sockets,
959 size_t socketsIndexHint) {
960 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
961 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
962
963 if (*exclusive != nullptr) return; // consistent with break below
964
965 for (size_t i = 0; i < sockets.size(); i++) {
966 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
967
Steven Moreland85e067b2021-05-26 17:43:53 +0000968 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000969 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
970 *available = socket;
971 continue;
972 }
973
Steven Moreland85e067b2021-05-26 17:43:53 +0000974 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000975 // (nested transactions)
976 if (exclusive && socket->exclusiveTid == tid) {
977 *exclusive = socket;
978 break; // consistent with return above
979 }
980 }
981}
982
983RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000984 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000985 // is using this fd, and it retains the right to it. So, we don't give up
986 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000987 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000988 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000989 }
990}
991
Pawan1c24f9c2022-08-26 23:23:15 +0000992bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
993 for (const auto& connection : connections) {
994 if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
995 return true;
996 }
997 }
998 return false;
999}
1000
1001bool RpcSession::hasActiveRequests() {
1002 RpcMutexUniqueLock _l(mMutex);
1003 if (hasActiveConnection(mConnections.mIncoming)) {
1004 return true;
1005 }
1006 if (hasActiveConnection(mConnections.mOutgoing)) {
1007 return true;
1008 }
1009 return mConnections.mWaitingThreads != 0;
1010}
1011
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001012} // namespace android