blob: c8aff63078a542845dac7706f7edb2983819c363 [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcSession"
18
19#include <binder/RpcSession.h>
20
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland12af6f72023-03-07 15:14:25 +000023#include <netinet/tcp.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000024#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +000030#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>
36#include <utils/String8.h>
37
Andrei Homescu9b58a462022-07-28 02:26:46 +000038#include "BuildFlags.h"
Yifan Hong8c950422021-08-05 17:13:55 -070039#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000040#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000041#include "RpcSocketAddress.h"
42#include "RpcState.h"
David Brazdil21c887c2022-09-23 12:25:18 +010043#include "RpcTransportUtils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000044#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070045#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000046
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000047#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070048#include <jni.h>
Jeongik Cha0c47d452022-10-20 00:07:55 +090049extern "C" JavaVM* AndroidRuntimeGetJavaVM();
Yifan Hongd258e682021-11-01 18:34:42 -070050#endif
51
Steven Morelandbdb53ab2021-05-05 17:57:41 +000052namespace android {
53
54using base::unique_fd;
55
Yifan Hongecf937d2021-08-11 17:29:28 -070056RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000057 LOG_RPC_DETAIL("RpcSession created %p", this);
58
Steven Moreland27a8bc72021-09-29 16:07:41 -070059 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000060}
61RpcSession::~RpcSession() {
62 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
63
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000064 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070065 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000066 "Should not be able to destroy a session with servers in use.");
67}
68
Yifan Hongecf937d2021-08-11 17:29:28 -070069sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070070 // Default is without TLS.
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +000071 return make(binder::os::makeDefaultRpcTransportCtxFactory());
Yifan Hongecf937d2021-08-11 17:29:28 -070072}
73
Yifan Hongfdd9f692021-09-09 15:12:52 -070074sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070075 auto ctx = rpcTransportCtxFactory->newClientCtx();
76 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070077 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000078}
79
Yifan Hong10423062021-10-08 16:26:32 -070080void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000081 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000082 LOG_ALWAYS_FATAL_IF(mStartedSetup,
83 "Must set max incoming threads before setting up connections");
Yifan Hong10423062021-10-08 16:26:32 -070084 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000085}
86
Yifan Hong10423062021-10-08 16:26:32 -070087size_t RpcSession::getMaxIncomingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000088 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070089 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000090}
91
Steven Morelande65f73c2023-03-04 01:34:50 +000092void RpcSession::setMaxOutgoingConnections(size_t connections) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000093 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000094 LOG_ALWAYS_FATAL_IF(mStartedSetup,
95 "Must set max outgoing threads before setting up connections");
Steven Morelande65f73c2023-03-04 01:34:50 +000096 mMaxOutgoingConnections = connections;
Yifan Hong1f44f982021-10-08 17:16:47 -070097}
98
99size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000100 RpcMutexLockGuard _l(mMutex);
Steven Morelande65f73c2023-03-04 01:34:50 +0000101 return mMaxOutgoingConnections;
Yifan Hong1f44f982021-10-08 17:16:47 -0700102}
103
Andrei Homescu9b58a462022-07-28 02:26:46 +0000104bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000105 if (!RpcState::validateProtocolVersion(version)) {
Steven Morelandbf57bce2021-07-26 15:26:12 -0700106 return false;
107 }
108
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000109 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000110 LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
111 "Must set protocol version before setting up connections");
Steven Moreland40b736e2021-07-30 14:37:10 -0700112 if (mProtocolVersion && version > *mProtocolVersion) {
113 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
114 *mProtocolVersion, version);
115 return false;
116 }
117
Steven Morelandbf57bce2021-07-26 15:26:12 -0700118 mProtocolVersion = version;
119 return true;
120}
121
Andrei Homescu9b58a462022-07-28 02:26:46 +0000122bool RpcSession::setProtocolVersion(uint32_t version) {
123 return setProtocolVersionInternal(version, true);
124}
125
Steven Morelandbf57bce2021-07-26 15:26:12 -0700126std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000127 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700128 return mProtocolVersion;
129}
130
Frederick Mayle69a0c992022-05-26 20:38:39 +0000131void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
Andrei Homescu9b58a462022-07-28 02:26:46 +0000132 RpcMutexLockGuard _l(mMutex);
133 LOG_ALWAYS_FATAL_IF(mStartedSetup,
134 "Must set file descriptor transport mode before setting up connections");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000135 mFileDescriptorTransportMode = mode;
136}
137
138RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
139 return mFileDescriptorTransportMode;
140}
141
Steven Moreland2372f9d2021-08-05 15:42:01 -0700142status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000143 return setupSocketClient(UnixSocketAddress(path));
144}
145
David Brazdil21c887c2022-09-23 12:25:18 +0100146status_t RpcSession::setupUnixDomainSocketBootstrapClient(unique_fd bootstrapFd) {
147 mBootstrapTransport =
148 mCtx->newTransport(RpcTransportFd(std::move(bootstrapFd)), mShutdownTrigger.get());
149 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
150 int socks[2];
151 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, socks) < 0) {
152 int savedErrno = errno;
153 ALOGE("Failed socketpair: %s", strerror(savedErrno));
154 return -savedErrno;
155 }
156 unique_fd clientFd(socks[0]), serverFd(socks[1]);
157
158 int zero = 0;
159 iovec iov{&zero, sizeof(zero)};
160 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
161 fds.push_back(std::move(serverFd));
162
163 status_t status = mBootstrapTransport->interruptableWriteFully(mShutdownTrigger.get(), &iov,
164 1, std::nullopt, &fds);
165 if (status != OK) {
166 ALOGE("Failed to send fd over bootstrap transport: %s", strerror(-status));
167 return status;
168 }
169
170 return initAndAddConnection(RpcTransportFd(std::move(clientFd)), sessionId, incoming);
171 });
172}
173
Steven Moreland2372f9d2021-08-05 15:42:01 -0700174status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000175 return setupSocketClient(VsockSocketAddress(cid, port));
176}
177
Steven Moreland2372f9d2021-08-05 15:42:01 -0700178status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700180 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
182 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700183 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184 }
185 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 -0700186 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000187}
188
Pawan49d74cb2022-08-03 21:19:11 +0000189status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
190 std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000191 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700192 if (!fd.ok()) {
193 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700194 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700195 }
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000196 if (auto res = binder::os::setNonBlocking(fd); !res.ok()) {
Yifan Hongb675ffe2021-08-05 16:37:17 -0700197 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
198 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
199 }
Pawan49d74cb2022-08-03 21:19:11 +0000200
Pawan3e0061c2022-08-26 21:08:34 +0000201 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000202 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000203 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
204 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700205 });
206}
207
Steven Moreland2372f9d2021-08-05 15:42:01 -0700208status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700209 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700210 if (auto status = initShutdownTrigger(); status != OK) return status;
211
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000212 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
213
214 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700215 int savedErrno = errno;
216 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
217 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000218 }
219
Pawan3e0061c2022-08-26 21:08:34 +0000220 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000221 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700222 if (server == nullptr) {
223 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700224 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700225 }
226 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000227}
228
229sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000230 ExclusiveConnection connection;
231 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
232 ConnectionUse::CLIENT, &connection);
233 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000234 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000235}
236
Steven Moreland1be91352021-05-11 22:12:15 +0000237status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000238 ExclusiveConnection connection;
239 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
240 ConnectionUse::CLIENT, &connection);
241 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000242 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000243}
244
Steven Morelandc9d7b532021-06-04 20:57:41 +0000245bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000246 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000247 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000248
249 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000250
Steven Morelandc9d7b532021-06-04 20:57:41 +0000251 if (wait) {
252 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700253 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700254
Steven Morelanda59937e2021-10-04 17:42:30 -0700255 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000256 }
257
258 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000259
Devin Moore66d5b7a2022-07-07 21:42:10 +0000260 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
261 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
262 statusToString(res).c_str());
263 }
264
Steven Moreland27a8bc72021-09-29 16:07:41 -0700265 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000266
Steven Moreland659416d2021-05-11 00:47:50 +0000267 return true;
268}
269
Steven Morelandf5174272021-05-25 00:39:28 +0000270status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000271 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000272 ExclusiveConnection connection;
273 status_t status =
274 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
275 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
276 : ConnectionUse::CLIENT,
277 &connection);
278 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000279 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000280 sp<RpcSession>::fromExisting(this), reply, flags);
281}
282
Steven Moreland4f622fe2021-09-13 17:38:09 -0700283status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000284 // target is 0 because this is used to free BpBinder objects
285 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700286}
287
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000288status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000289 ExclusiveConnection connection;
290 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
291 ConnectionUse::CLIENT_REFCOUNT, &connection);
292 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000293 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
294 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295}
296
297status_t RpcSession::readId() {
298 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000299 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
301 }
302
Steven Moreland195edb82021-06-08 02:44:39 +0000303 ExclusiveConnection connection;
304 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
305 ConnectionUse::CLIENT, &connection);
306 if (status != OK) return status;
307
Steven Moreland826367f2021-09-10 14:05:31 -0700308 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309 if (status != OK) return status;
310
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000311 LOG_RPC_DETAIL("RpcSession %p has id %s", this, HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000312 return OK;
313}
314
Steven Morelanddd67b942021-07-23 17:15:41 -0700315void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000316 const sp<RpcSession>& session) {
317 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000318}
319
Steven Moreland19fc9f72021-06-10 03:57:30 +0000320void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000321 mShutdownCount += 1;
Steven Moreland659416d2021-05-11 00:47:50 +0000322 mCv.notify_all();
323}
324
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000325void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700326 const sp<RpcSession>& session) {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000327 while (mShutdownCount < session->mConnections.mMaxIncoming) {
Steven Moreland659416d2021-05-11 00:47:50 +0000328 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700329 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
Steven Moreland8b7a7382022-10-08 04:00:54 +0000330 "still %zu/%zu fully shutdown.",
331 session->mConnections.mIncoming.size(), mShutdownCount.load(),
332 session->mConnections.mMaxIncoming);
Steven Moreland659416d2021-05-11 00:47:50 +0000333 }
334 }
335}
336
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000337void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
338 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000339
Steven Morelanda63ff932021-05-12 00:03:15 +0000340 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000341 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700342 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000343 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000344}
Steven Morelanda63ff932021-05-12 00:03:15 +0000345
Yifan Hong702115c2021-06-24 15:39:18 -0700346RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
347 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348 // must be registered to allow arbitrary client code executing commands to
349 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700350 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351
Steven Morelanddd67b942021-07-23 17:15:41 -0700352 status_t status;
353
354 if (connection == nullptr) {
355 status = DEAD_OBJECT;
356 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700357 status =
358 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700359 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000361 return PreJoinSetupResult{
362 .connection = std::move(connection),
363 .status = status,
364 };
365}
366
Yifan Hong194acf22021-06-29 18:44:56 -0700367namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000368#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700369class JavaThreadAttacher {};
370#else
Yifan Hong194acf22021-06-29 18:44:56 -0700371// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
372// Android Runtime doesn't exist, no-op.
373class JavaThreadAttacher {
374public:
375 JavaThreadAttacher() {
376 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
377 // libbinder.
378 auto vm = getJavaVM();
379 if (vm == nullptr) return;
380
381 char threadName[16];
382 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
383 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
384 memcpy(threadName, defaultThreadName,
385 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
386 }
387 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
388 JavaVMAttachArgs args;
389 args.version = JNI_VERSION_1_2;
390 args.name = threadName;
391 args.group = nullptr;
392 JNIEnv* env;
393
394 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
395 "Cannot attach thread %s to JVM", threadName);
396 mAttached = true;
397 }
398 ~JavaThreadAttacher() {
399 if (!mAttached) return;
400 auto vm = getJavaVM();
401 LOG_ALWAYS_FATAL_IF(vm == nullptr,
402 "Unable to detach thread. No JavaVM, but it was present before!");
403
404 LOG_RPC_DETAIL("Detaching current thread from JVM");
Steven Morelandd0c9a172022-10-24 15:46:21 +0000405 int ret = vm->DetachCurrentThread();
406 if (ret == JNI_OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700407 mAttached = false;
408 } else {
Steven Morelandd0c9a172022-10-24 15:46:21 +0000409 ALOGW("Unable to detach current thread from JVM (%d)", ret);
Yifan Hong194acf22021-06-29 18:44:56 -0700410 }
411 }
412
413private:
414 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
415 bool mAttached = false;
416
417 static JavaVM* getJavaVM() {
418 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
419 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
420 if (fn == nullptr) return nullptr;
421 return fn();
422 }
423};
Yifan Hongd258e682021-11-01 18:34:42 -0700424#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700425} // namespace
426
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000427void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
428 sp<RpcConnection>& connection = setupResult.connection;
429
430 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700431 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700432 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000433 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000434 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000435 RpcState::CommandType::ANY);
436 if (status != OK) {
437 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
438 statusToString(status).c_str());
439 break;
440 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000442 } else {
443 ALOGE("Connection failed to init, closing with status %s",
444 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445 }
446
Steven Moreland659416d2021-05-11 00:47:50 +0000447 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000448 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000449 RpcMutexLockGuard _l(session->mMutex);
450 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700451 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000452 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700453 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000454
Steven Moreland659416d2021-05-11 00:47:50 +0000455 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000456 }
457
Steven Morelanddd67b942021-07-23 17:15:41 -0700458 // done after all cleanup, since session shutdown progresses via callbacks here
459 if (connection != nullptr) {
460 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
461 "bad state: connection object guaranteed to be in list");
462 }
463
Steven Moreland659416d2021-05-11 00:47:50 +0000464 session = nullptr;
465
466 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000467 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000468 }
469}
470
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000471sp<RpcServer> RpcSession::server() {
472 RpcServer* unsafeServer = mForServer.unsafe_get();
473 sp<RpcServer> server = mForServer.promote();
474
475 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
476 "wp<> is to avoid strong cycle only");
477 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000478}
479
Steven Moreland826367f2021-09-10 14:05:31 -0700480status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
481 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000482 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000483 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000484 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
485 mStartedSetup = true;
486
487 if constexpr (!kEnableRpcThreads) {
488 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
489 "Incoming threads are not supported on single-threaded libbinder");
490 // mMaxIncomingThreads should not change from here to its use below,
491 // since we set mStartedSetup==true and setMaxIncomingThreads checks
492 // for that
493 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700495
Yifan Hong832521e2021-08-05 14:55:40 -0700496 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000497
Steven Moreland27a8bc72021-09-29 16:07:41 -0700498 auto oldProtocolVersion = mProtocolVersion;
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +0000499 auto cleanup = base::ScopeGuard([&] {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700500 // if any threads are started, shut them down
501 (void)shutdownAndWait(true);
502
503 mShutdownListener = nullptr;
504 mEventListener.clear();
505
506 mId.clear();
507
508 mShutdownTrigger = nullptr;
509 mRpcBinderState = std::make_unique<RpcState>();
510
511 // protocol version may have been downgraded - if we reuse this object
512 // to connect to another server, force that server to request a
513 // downgrade again
514 mProtocolVersion = oldProtocolVersion;
515
Steven Morelanda59937e2021-10-04 17:42:30 -0700516 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000517
518 // clear mStartedSetup so that we can reuse this RpcSession
519 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700520 });
521
Steven Moreland826367f2021-09-10 14:05:31 -0700522 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000523
Steven Morelandbf57bce2021-07-26 15:26:12 -0700524 {
525 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700526 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
527 ConnectionUse::CLIENT, &connection);
528 status != OK)
529 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700530
531 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700532 if (status_t status =
533 state()->readNewSessionResponse(connection.get(),
534 sp<RpcSession>::fromExisting(this), &version);
535 status != OK)
536 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000537 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700538 }
539
Steven Morelanda5036f02021-06-08 02:26:57 +0000540 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000541 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000542 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000543 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700544 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000545 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000547 }
548
549 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700550 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000551 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700552 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000553 }
554
Steven Morelande65f73c2023-03-04 01:34:50 +0000555 size_t outgoingConnections = std::min(numThreadsAvailable, mMaxOutgoingConnections);
556 ALOGI_IF(outgoingConnections != numThreadsAvailable,
Yifan Hong1f44f982021-10-08 17:16:47 -0700557 "Server hints client to start %zu outgoing threads, but client will only start %zu "
558 "because it is preconfigured to start at most %zu outgoing threads.",
Steven Morelande65f73c2023-03-04 01:34:50 +0000559 numThreadsAvailable, outgoingConnections, mMaxOutgoingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700560
Steven Morelanda5036f02021-06-08 02:26:57 +0000561 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000562 // instead of all at once - the other side should be responsible for setting
563 // up additional connections. We need to create at least one (unless 0 are
564 // requested to be set) in order to allow the other side to reliably make
565 // any requests at all.
566
Steven Moreland4198a122021-08-03 17:37:58 -0700567 // we've already setup one client
Steven Morelande65f73c2023-03-04 01:34:50 +0000568 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing connections (server max: "
569 "%zu) and %zu incoming threads",
570 outgoingConnections, numThreadsAvailable, mMaxIncomingThreads);
571 for (size_t i = 0; i + 1 < outgoingConnections; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700572 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700573 }
574
Yifan Hong10423062021-10-08 16:26:32 -0700575 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700576 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000577 }
578
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +0000579 cleanup.Disable();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700580
Steven Moreland2372f9d2021-08-05 15:42:01 -0700581 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000582}
583
Steven Moreland2372f9d2021-08-05 15:42:01 -0700584status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700585 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700586 return setupOneSocketConnection(addr, sessionId, incoming);
587 });
588}
589
Steven Moreland2372f9d2021-08-05 15:42:01 -0700590status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700591 const std::vector<uint8_t>& sessionId,
592 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000593 for (size_t tries = 0; tries < 5; tries++) {
594 if (tries > 0) usleep(10000);
595
Yifan Hongb675ffe2021-08-05 16:37:17 -0700596 unique_fd serverFd(TEMP_FAILURE_RETRY(
597 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000598 if (serverFd == -1) {
599 int savedErrno = errno;
600 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
601 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700602 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000603 }
604
Steven Moreland12af6f72023-03-07 15:14:25 +0000605 if (addr.addr()->sa_family == AF_INET || addr.addr()->sa_family == AF_INET6) {
606 int noDelay = 1;
607 int result =
608 setsockopt(serverFd.get(), IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay));
609 if (result < 0) {
610 int savedErrno = errno;
611 ALOGE("Could not set TCP_NODELAY on %s: %s", addr.toString().c_str(),
612 strerror(savedErrno));
613 return -savedErrno;
614 }
615 }
616
Pawan3e0061c2022-08-26 21:08:34 +0000617 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000618
619 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700620 int connErrno = errno;
621 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
622 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
623 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Pawan49d74cb2022-08-03 21:19:11 +0000624 status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700625 if (pollStatus != OK) {
626 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
627 statusToString(pollStatus).c_str());
628 return pollStatus;
629 }
630 // Set connErrno to the errno that connect() would have set if the fd were blocking.
631 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000632 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
633 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700634 if (ret == -1) {
635 int savedErrno = errno;
636 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
637 "(Original error from connect() is: %s)",
638 strerror(savedErrno), strerror(connErrno));
639 return -savedErrno;
640 }
641 // Retrieved the real connErrno as if connect() was called with a blocking socket
642 // fd. Continue checking connErrno.
643 }
644 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000645 ALOGW("Connection reset on %s", addr.toString().c_str());
646 continue;
647 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700648 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
649 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700650 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700651 strerror(connErrno));
652 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700653 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000654 }
Pawan49d74cb2022-08-03 21:19:11 +0000655 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
656 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700657
Pawan49d74cb2022-08-03 21:19:11 +0000658 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000659 }
660
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000661 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700662 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000663}
664
Pawan3e0061c2022-08-26 21:08:34 +0000665status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700666 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700667 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700668 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700669 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700670 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700671 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700672 }
673
674 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
675
Steven Moreland826367f2021-09-10 14:05:31 -0700676 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
677 ALOGE("Session ID too big %zu", sessionId.size());
678 return BAD_VALUE;
679 }
680
Steven Moreland4198a122021-08-03 17:37:58 -0700681 RpcConnectionHeader header{
682 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
683 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000684 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700685 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700686 };
Steven Moreland4198a122021-08-03 17:37:58 -0700687
Steven Moreland826367f2021-09-10 14:05:31 -0700688 if (incoming) {
689 header.options |= RPC_CONNECTION_OPTION_INCOMING;
690 }
Steven Moreland4198a122021-08-03 17:37:58 -0700691
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000692 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000693 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
694 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700695 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700696 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700697 statusToString(sendHeaderStatus).c_str());
698 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700699 }
700
Steven Moreland826367f2021-09-10 14:05:31 -0700701 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000702 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
703 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000704 auto sendSessionIdStatus =
705 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
706 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700707 if (sendSessionIdStatus != OK) {
708 ALOGE("Could not write session ID ('%s') to socket: %s",
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000709 HexString(sessionId.data(), sessionId.size()).c_str(),
Steven Moreland826367f2021-09-10 14:05:31 -0700710 statusToString(sendSessionIdStatus).c_str());
711 return sendSessionIdStatus;
712 }
713 }
714
Steven Moreland4198a122021-08-03 17:37:58 -0700715 LOG_RPC_DETAIL("Socket at client: header sent");
716
717 if (incoming) {
718 return addIncomingConnection(std::move(server));
719 } else {
720 return addOutgoingConnection(std::move(server), true /*init*/);
721 }
722}
723
Steven Moreland2372f9d2021-08-05 15:42:01 -0700724status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000725 RpcMutex mutex;
726 RpcConditionVariable joinCv;
727 RpcMutexUniqueLock lock(mutex);
728 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000729 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
730 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000731 thread = RpcMaybeThread([&]() {
732 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700733 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000734 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
735 sp<RpcSession> session = thiz;
736 session->preJoinThreadOwnership(std::move(thread));
737
738 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700739 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000740
741 ownershipTransferred = true;
742 threadLock.unlock();
743 joinCv.notify_one();
744 // do not use & vars below
745
746 RpcSession::join(std::move(session), std::move(setupResult));
747 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000748 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000749 joinCv.wait(lock, [&] { return ownershipTransferred; });
750 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700751 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000752}
753
Yifan Hong832521e2021-08-05 14:55:40 -0700754status_t RpcSession::initShutdownTrigger() {
755 // first client connection added, but setForServer not called, so
756 // initializaing for a client.
757 if (mShutdownTrigger == nullptr) {
758 mShutdownTrigger = FdTrigger::make();
759 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
760 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
761 }
762 return OK;
763}
764
Steven Moreland2372f9d2021-08-05 15:42:01 -0700765status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000766 sp<RpcConnection> connection = sp<RpcConnection>::make();
767 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000768 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700769 connection->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000770 connection->exclusiveTid = binder::os::GetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700771 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000772 }
773
Steven Morelandb86e26b2021-06-12 00:35:58 +0000774 status_t status = OK;
775 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700776 status =
777 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000778 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000779
Andrei Homescuc8490872022-06-23 05:18:51 +0000780 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000781
Steven Moreland2372f9d2021-08-05 15:42:01 -0700782 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000783}
784
Steven Morelanda8b44292021-06-08 01:27:53 +0000785bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700786 const std::vector<uint8_t>& sessionId,
787 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000788 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
789 LOG_ALWAYS_FATAL_IF(server == nullptr);
790 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
791 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000792 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000793 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000794
795 mShutdownTrigger = FdTrigger::make();
796 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000797
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000798 mId = sessionId;
799 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000800 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700801 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000802 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000803}
804
Yifan Hong702115c2021-06-24 15:39:18 -0700805sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
806 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000807 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700808
Yifan Hong10423062021-10-08 16:26:32 -0700809 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700810 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700811 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700812 return nullptr;
813 }
814
Steven Morelanddd67b942021-07-23 17:15:41 -0700815 // Don't accept any more connections, some have shutdown. Usually this
816 // happens when new connections are still being established as part of a
817 // very short-lived session which shuts down after it already started
818 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700819 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700820 return nullptr;
821 }
822
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000823 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700824 session->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000825 session->exclusiveTid = binder::os::GetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700826
Steven Morelanda59937e2021-10-04 17:42:30 -0700827 mConnections.mIncoming.push_back(session);
828 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829
830 return session;
831}
832
Steven Moreland19fc9f72021-06-10 03:57:30 +0000833bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000834 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700835 if (auto it =
836 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
837 it != mConnections.mIncoming.end()) {
838 mConnections.mIncoming.erase(it);
839 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000840 sp<EventListener> listener = mEventListener.promote();
841 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700842 _l.unlock();
843 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000844 }
Steven Morelandee78e762021-05-05 21:12:51 +0000845 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000846 return true;
847 }
848 return false;
849}
850
Andrei Homescuc8490872022-06-23 05:18:51 +0000851void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000852 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000853 connection->exclusiveTid = std::nullopt;
854 if (mConnections.mWaitingThreads > 0) {
855 _l.unlock();
856 mAvailableConnectionCv.notify_one();
857 }
858}
859
Yifan Hong9734cfc2021-09-13 16:14:09 -0700860std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700861 return mCtx->getCertificate(format);
862}
863
Steven Moreland195edb82021-06-08 02:44:39 +0000864status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
865 ExclusiveConnection* connection) {
866 connection->mSession = session;
867 connection->mConnection = nullptr;
868 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000869
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000870 uint64_t tid = binder::os::GetThreadId();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000871 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000872
Steven Morelanda59937e2021-10-04 17:42:30 -0700873 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000874 while (true) {
875 sp<RpcConnection> exclusive;
876 sp<RpcConnection> available;
877
878 // CHECK FOR DEDICATED CLIENT SOCKET
879 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000880 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700881 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
882 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000883
884 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700885 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000886 //
887 // Imagine we have more than one thread in play, and a single thread
888 // sends a synchronous, then an asynchronous command. Imagine the
889 // asynchronous command is sent on the first client connection. Then, if
890 // we naively send a synchronous command to that same connection, the
891 // thread on the far side might be busy processing the asynchronous
892 // command. So, we move to considering the second available thread
893 // for subsequent calls.
894 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700895 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
896 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000897 }
898
Steven Morelandc7d40132021-06-10 03:42:11 +0000899 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000900 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000901 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000902 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000903 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700904 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000905
906 // asynchronous calls cannot be nested, we currently allow ref count
907 // calls to be nested (so that you can use this without having extra
908 // threads). Note 'drainCommands' is used so that these ref counts can't
909 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000910 if (exclusiveIncoming != nullptr) {
911 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000912 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000913 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000914 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
915 // prefer available socket, but if we don't have one, don't
916 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000917 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000918 }
919 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000920 }
921
Steven Moreland85e067b2021-05-26 17:43:53 +0000922 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000923 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000924 connection->mConnection = exclusive;
925 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000926 break;
927 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000928 connection->mConnection = available;
929 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000930 break;
931 }
932
Steven Morelanda59937e2021-10-04 17:42:30 -0700933 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000934 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
935 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
936 "reason: %d. Incoming connections: %zu. %s.",
937 static_cast<int>(use), session->mConnections.mIncoming.size(),
938 (session->server()
939 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
940 "for the corresponding client"
Steven Morelandfeb13e82023-03-01 01:25:33 +0000941 : "This is a client session, so see "
942 "RpcSession::setMaxOutgoingConnections "
Steven Moreland25d9cc52022-03-10 23:11:56 +0000943 "for this client or RpcServer::setMaxThreads for the corresponding "
944 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000945 return WOULD_BLOCK;
946 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000947
Steven Moreland85e067b2021-05-26 17:43:53 +0000948 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700949 session->mConnections.mOutgoing.size(),
950 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000951 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000952 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700953 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000954
955 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000956}
957
Andrei Homescue922b232022-04-23 03:41:09 +0000958void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000959 sp<RpcConnection>* available,
960 std::vector<sp<RpcConnection>>& sockets,
961 size_t socketsIndexHint) {
962 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
963 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
964
965 if (*exclusive != nullptr) return; // consistent with break below
966
967 for (size_t i = 0; i < sockets.size(); i++) {
968 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
969
Steven Moreland85e067b2021-05-26 17:43:53 +0000970 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000971 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
972 *available = socket;
973 continue;
974 }
975
Steven Moreland85e067b2021-05-26 17:43:53 +0000976 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000977 // (nested transactions)
978 if (exclusive && socket->exclusiveTid == tid) {
979 *exclusive = socket;
980 break; // consistent with return above
981 }
982 }
983}
984
985RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000986 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000987 // is using this fd, and it retains the right to it. So, we don't give up
988 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000989 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000990 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000991 }
992}
993
Pawan1c24f9c2022-08-26 23:23:15 +0000994bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
995 for (const auto& connection : connections) {
996 if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
997 return true;
998 }
999 }
1000 return false;
1001}
1002
1003bool RpcSession::hasActiveRequests() {
1004 RpcMutexUniqueLock _l(mMutex);
1005 if (hasActiveConnection(mConnections.mIncoming)) {
1006 return true;
1007 }
1008 if (hasActiveConnection(mConnections.mOutgoing)) {
1009 return true;
1010 }
1011 return mConnections.mWaitingThreads != 0;
1012}
1013
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001014} // namespace android