blob: 524b54c31cd173a31cfd267f3bc21845383eac37 [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcSession"
18
19#include <binder/RpcSession.h>
20
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland12af6f72023-03-07 15:14:25 +000023#include <netinet/tcp.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000024#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070030#include <binder/BpBinder.h>
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +000031#include <binder/Functional.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000032#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000033#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/Stability.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000036#include <utils/Compat.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000037#include <utils/String8.h>
38
Andrei Homescu9b58a462022-07-28 02:26:46 +000039#include "BuildFlags.h"
Yifan Hong8c950422021-08-05 17:13:55 -070040#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000041#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000042#include "RpcSocketAddress.h"
43#include "RpcState.h"
David Brazdil21c887c2022-09-23 12:25:18 +010044#include "RpcTransportUtils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070046#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000047
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000048#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070049#include <jni.h>
Jeongik Cha0c47d452022-10-20 00:07:55 +090050extern "C" JavaVM* AndroidRuntimeGetJavaVM();
Yifan Hongd258e682021-11-01 18:34:42 -070051#endif
52
Steven Morelandbdb53ab2021-05-05 17:57:41 +000053namespace android {
54
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +000055using namespace android::binder::impl;
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056using base::unique_fd;
57
Yifan Hongecf937d2021-08-11 17:29:28 -070058RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059 LOG_RPC_DETAIL("RpcSession created %p", this);
60
Steven Moreland27a8bc72021-09-29 16:07:41 -070061 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000062}
63RpcSession::~RpcSession() {
64 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
65
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000066 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070067 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000068 "Should not be able to destroy a session with servers in use.");
69}
70
Yifan Hongecf937d2021-08-11 17:29:28 -070071sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070072 // Default is without TLS.
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +000073 return make(binder::os::makeDefaultRpcTransportCtxFactory());
Yifan Hongecf937d2021-08-11 17:29:28 -070074}
75
Yifan Hongfdd9f692021-09-09 15:12:52 -070076sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070077 auto ctx = rpcTransportCtxFactory->newClientCtx();
78 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070079 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000080}
81
Yifan Hong10423062021-10-08 16:26:32 -070082void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000083 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000084 LOG_ALWAYS_FATAL_IF(mStartedSetup,
85 "Must set max incoming threads before setting up connections");
Yifan Hong10423062021-10-08 16:26:32 -070086 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000087}
88
Yifan Hong10423062021-10-08 16:26:32 -070089size_t RpcSession::getMaxIncomingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000090 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070091 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000092}
93
Steven Morelande65f73c2023-03-04 01:34:50 +000094void RpcSession::setMaxOutgoingConnections(size_t connections) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000095 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000096 LOG_ALWAYS_FATAL_IF(mStartedSetup,
97 "Must set max outgoing threads before setting up connections");
Steven Morelande65f73c2023-03-04 01:34:50 +000098 mMaxOutgoingConnections = connections;
Yifan Hong1f44f982021-10-08 17:16:47 -070099}
100
101size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000102 RpcMutexLockGuard _l(mMutex);
Steven Morelande65f73c2023-03-04 01:34:50 +0000103 return mMaxOutgoingConnections;
Yifan Hong1f44f982021-10-08 17:16:47 -0700104}
105
Andrei Homescu9b58a462022-07-28 02:26:46 +0000106bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000107 if (!RpcState::validateProtocolVersion(version)) {
Steven Morelandbf57bce2021-07-26 15:26:12 -0700108 return false;
109 }
110
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000111 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000112 LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
113 "Must set protocol version before setting up connections");
Steven Moreland40b736e2021-07-30 14:37:10 -0700114 if (mProtocolVersion && version > *mProtocolVersion) {
115 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
116 *mProtocolVersion, version);
117 return false;
118 }
119
Steven Morelandbf57bce2021-07-26 15:26:12 -0700120 mProtocolVersion = version;
121 return true;
122}
123
Andrei Homescu9b58a462022-07-28 02:26:46 +0000124bool RpcSession::setProtocolVersion(uint32_t version) {
125 return setProtocolVersionInternal(version, true);
126}
127
Steven Morelandbf57bce2021-07-26 15:26:12 -0700128std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000129 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700130 return mProtocolVersion;
131}
132
Frederick Mayle69a0c992022-05-26 20:38:39 +0000133void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
Andrei Homescu9b58a462022-07-28 02:26:46 +0000134 RpcMutexLockGuard _l(mMutex);
135 LOG_ALWAYS_FATAL_IF(mStartedSetup,
136 "Must set file descriptor transport mode before setting up connections");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000137 mFileDescriptorTransportMode = mode;
138}
139
140RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
141 return mFileDescriptorTransportMode;
142}
143
Steven Moreland2372f9d2021-08-05 15:42:01 -0700144status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145 return setupSocketClient(UnixSocketAddress(path));
146}
147
David Brazdil21c887c2022-09-23 12:25:18 +0100148status_t RpcSession::setupUnixDomainSocketBootstrapClient(unique_fd bootstrapFd) {
149 mBootstrapTransport =
150 mCtx->newTransport(RpcTransportFd(std::move(bootstrapFd)), mShutdownTrigger.get());
151 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
152 int socks[2];
153 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, socks) < 0) {
154 int savedErrno = errno;
155 ALOGE("Failed socketpair: %s", strerror(savedErrno));
156 return -savedErrno;
157 }
158 unique_fd clientFd(socks[0]), serverFd(socks[1]);
159
160 int zero = 0;
161 iovec iov{&zero, sizeof(zero)};
162 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
163 fds.push_back(std::move(serverFd));
164
165 status_t status = mBootstrapTransport->interruptableWriteFully(mShutdownTrigger.get(), &iov,
166 1, std::nullopt, &fds);
167 if (status != OK) {
168 ALOGE("Failed to send fd over bootstrap transport: %s", strerror(-status));
169 return status;
170 }
171
172 return initAndAddConnection(RpcTransportFd(std::move(clientFd)), sessionId, incoming);
173 });
174}
175
Steven Moreland2372f9d2021-08-05 15:42:01 -0700176status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 return setupSocketClient(VsockSocketAddress(cid, port));
178}
179
Steven Moreland2372f9d2021-08-05 15:42:01 -0700180status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700182 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
184 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700185 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 }
187 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 -0700188 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189}
190
Pawan49d74cb2022-08-03 21:19:11 +0000191status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
192 std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000193 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700194 if (!fd.ok()) {
195 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700196 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700197 }
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000198 if (auto res = binder::os::setNonBlocking(fd); !res.ok()) {
Yifan Hongb675ffe2021-08-05 16:37:17 -0700199 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
200 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
201 }
Pawan49d74cb2022-08-03 21:19:11 +0000202
Pawan3e0061c2022-08-26 21:08:34 +0000203 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000204 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000205 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
206 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700207 });
208}
209
Steven Moreland2372f9d2021-08-05 15:42:01 -0700210status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700211 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700212 if (auto status = initShutdownTrigger(); status != OK) return status;
213
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000214 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
215
216 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700217 int savedErrno = errno;
218 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
219 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000220 }
221
Pawan3e0061c2022-08-26 21:08:34 +0000222 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000223 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700224 if (server == nullptr) {
225 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700226 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700227 }
228 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000229}
230
231sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000232 ExclusiveConnection connection;
233 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
234 ConnectionUse::CLIENT, &connection);
235 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000236 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000237}
238
Steven Moreland1be91352021-05-11 22:12:15 +0000239status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000240 ExclusiveConnection connection;
241 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
242 ConnectionUse::CLIENT, &connection);
243 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000244 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000245}
246
Steven Morelandc9d7b532021-06-04 20:57:41 +0000247bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000248 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000249 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000250
251 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000252
Steven Morelandc9d7b532021-06-04 20:57:41 +0000253 if (wait) {
254 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700255 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700256
Steven Morelanda59937e2021-10-04 17:42:30 -0700257 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000258 }
259
260 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000261
Devin Moore66d5b7a2022-07-07 21:42:10 +0000262 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
263 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
264 statusToString(res).c_str());
265 }
266
Steven Moreland27a8bc72021-09-29 16:07:41 -0700267 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000268
Steven Moreland659416d2021-05-11 00:47:50 +0000269 return true;
270}
271
Steven Morelandf5174272021-05-25 00:39:28 +0000272status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000273 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000274 ExclusiveConnection connection;
275 status_t status =
276 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
277 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
278 : ConnectionUse::CLIENT,
279 &connection);
280 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000281 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282 sp<RpcSession>::fromExisting(this), reply, flags);
283}
284
Steven Moreland4f622fe2021-09-13 17:38:09 -0700285status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000286 // target is 0 because this is used to free BpBinder objects
287 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700288}
289
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000290status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000291 ExclusiveConnection connection;
292 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
293 ConnectionUse::CLIENT_REFCOUNT, &connection);
294 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000295 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
296 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000297}
298
299status_t RpcSession::readId() {
300 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000301 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
303 }
304
Steven Moreland195edb82021-06-08 02:44:39 +0000305 ExclusiveConnection connection;
306 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
307 ConnectionUse::CLIENT, &connection);
308 if (status != OK) return status;
309
Steven Moreland826367f2021-09-10 14:05:31 -0700310 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311 if (status != OK) return status;
312
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000313 LOG_RPC_DETAIL("RpcSession %p has id %s", this, HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314 return OK;
315}
316
Steven Morelanddd67b942021-07-23 17:15:41 -0700317void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000318 const sp<RpcSession>& session) {
319 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000320}
321
Steven Moreland19fc9f72021-06-10 03:57:30 +0000322void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000323 mShutdownCount += 1;
Steven Moreland659416d2021-05-11 00:47:50 +0000324 mCv.notify_all();
325}
326
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000327void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700328 const sp<RpcSession>& session) {
Steven Moreland8b7a7382022-10-08 04:00:54 +0000329 while (mShutdownCount < session->mConnections.mMaxIncoming) {
Steven Moreland659416d2021-05-11 00:47:50 +0000330 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700331 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
Steven Moreland8b7a7382022-10-08 04:00:54 +0000332 "still %zu/%zu fully shutdown.",
333 session->mConnections.mIncoming.size(), mShutdownCount.load(),
334 session->mConnections.mMaxIncoming);
Steven Moreland659416d2021-05-11 00:47:50 +0000335 }
336 }
337}
338
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000339void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
340 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000341
Steven Morelanda63ff932021-05-12 00:03:15 +0000342 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000343 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700344 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000345 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000346}
Steven Morelanda63ff932021-05-12 00:03:15 +0000347
Yifan Hong702115c2021-06-24 15:39:18 -0700348RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
349 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000350 // must be registered to allow arbitrary client code executing commands to
351 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700352 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353
Steven Morelanddd67b942021-07-23 17:15:41 -0700354 status_t status;
355
356 if (connection == nullptr) {
357 status = DEAD_OBJECT;
358 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700359 status =
360 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700361 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000363 return PreJoinSetupResult{
364 .connection = std::move(connection),
365 .status = status,
366 };
367}
368
Yifan Hong194acf22021-06-29 18:44:56 -0700369namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000370#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700371class JavaThreadAttacher {};
372#else
Yifan Hong194acf22021-06-29 18:44:56 -0700373// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
374// Android Runtime doesn't exist, no-op.
375class JavaThreadAttacher {
376public:
377 JavaThreadAttacher() {
378 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
379 // libbinder.
380 auto vm = getJavaVM();
381 if (vm == nullptr) return;
382
383 char threadName[16];
384 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
385 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
386 memcpy(threadName, defaultThreadName,
387 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
388 }
389 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
390 JavaVMAttachArgs args;
391 args.version = JNI_VERSION_1_2;
392 args.name = threadName;
393 args.group = nullptr;
394 JNIEnv* env;
395
396 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
397 "Cannot attach thread %s to JVM", threadName);
398 mAttached = true;
399 }
400 ~JavaThreadAttacher() {
401 if (!mAttached) return;
402 auto vm = getJavaVM();
403 LOG_ALWAYS_FATAL_IF(vm == nullptr,
404 "Unable to detach thread. No JavaVM, but it was present before!");
405
406 LOG_RPC_DETAIL("Detaching current thread from JVM");
Steven Morelandd0c9a172022-10-24 15:46:21 +0000407 int ret = vm->DetachCurrentThread();
408 if (ret == JNI_OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700409 mAttached = false;
410 } else {
Steven Morelandd0c9a172022-10-24 15:46:21 +0000411 ALOGW("Unable to detach current thread from JVM (%d)", ret);
Yifan Hong194acf22021-06-29 18:44:56 -0700412 }
413 }
414
415private:
416 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
417 bool mAttached = false;
418
419 static JavaVM* getJavaVM() {
420 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
421 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
422 if (fn == nullptr) return nullptr;
423 return fn();
424 }
425};
Yifan Hongd258e682021-11-01 18:34:42 -0700426#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700427} // namespace
428
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000429void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
430 sp<RpcConnection>& connection = setupResult.connection;
431
432 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700433 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700434 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000435 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000436 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000437 RpcState::CommandType::ANY);
438 if (status != OK) {
439 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
440 statusToString(status).c_str());
441 break;
442 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000443 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000444 } else {
445 ALOGE("Connection failed to init, closing with status %s",
446 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447 }
448
Steven Moreland659416d2021-05-11 00:47:50 +0000449 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000450 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000451 RpcMutexLockGuard _l(session->mMutex);
452 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700453 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000454 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700455 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000456
Steven Moreland659416d2021-05-11 00:47:50 +0000457 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000458 }
459
Steven Morelanddd67b942021-07-23 17:15:41 -0700460 // done after all cleanup, since session shutdown progresses via callbacks here
461 if (connection != nullptr) {
462 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
463 "bad state: connection object guaranteed to be in list");
464 }
465
Steven Moreland659416d2021-05-11 00:47:50 +0000466 session = nullptr;
467
468 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000469 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000470 }
471}
472
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000473sp<RpcServer> RpcSession::server() {
474 RpcServer* unsafeServer = mForServer.unsafe_get();
475 sp<RpcServer> server = mForServer.promote();
476
477 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
478 "wp<> is to avoid strong cycle only");
479 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480}
481
Steven Moreland826367f2021-09-10 14:05:31 -0700482status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
483 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000485 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000486 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
487 mStartedSetup = true;
488
489 if constexpr (!kEnableRpcThreads) {
490 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
491 "Incoming threads are not supported on single-threaded libbinder");
492 // mMaxIncomingThreads should not change from here to its use below,
493 // since we set mStartedSetup==true and setMaxIncomingThreads checks
494 // for that
495 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000496 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700497
Yifan Hong832521e2021-08-05 14:55:40 -0700498 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499
Steven Moreland27a8bc72021-09-29 16:07:41 -0700500 auto oldProtocolVersion = mProtocolVersion;
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +0000501 auto cleanup = make_scope_guard([&] {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700502 // if any threads are started, shut them down
503 (void)shutdownAndWait(true);
504
505 mShutdownListener = nullptr;
506 mEventListener.clear();
507
508 mId.clear();
509
510 mShutdownTrigger = nullptr;
511 mRpcBinderState = std::make_unique<RpcState>();
512
513 // protocol version may have been downgraded - if we reuse this object
514 // to connect to another server, force that server to request a
515 // downgrade again
516 mProtocolVersion = oldProtocolVersion;
517
Steven Morelanda59937e2021-10-04 17:42:30 -0700518 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000519
520 // clear mStartedSetup so that we can reuse this RpcSession
521 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700522 });
523
Steven Moreland826367f2021-09-10 14:05:31 -0700524 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525
Steven Morelandbf57bce2021-07-26 15:26:12 -0700526 {
527 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700528 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
529 ConnectionUse::CLIENT, &connection);
530 status != OK)
531 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700532
533 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700534 if (status_t status =
535 state()->readNewSessionResponse(connection.get(),
536 sp<RpcSession>::fromExisting(this), &version);
537 status != OK)
538 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000539 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700540 }
541
Steven Morelanda5036f02021-06-08 02:26:57 +0000542 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000545 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700546 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000547 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700548 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000549 }
550
551 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700552 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000553 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700554 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000555 }
556
Steven Morelande65f73c2023-03-04 01:34:50 +0000557 size_t outgoingConnections = std::min(numThreadsAvailable, mMaxOutgoingConnections);
558 ALOGI_IF(outgoingConnections != numThreadsAvailable,
Yifan Hong1f44f982021-10-08 17:16:47 -0700559 "Server hints client to start %zu outgoing threads, but client will only start %zu "
560 "because it is preconfigured to start at most %zu outgoing threads.",
Steven Morelande65f73c2023-03-04 01:34:50 +0000561 numThreadsAvailable, outgoingConnections, mMaxOutgoingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700562
Steven Morelanda5036f02021-06-08 02:26:57 +0000563 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000564 // instead of all at once - the other side should be responsible for setting
565 // up additional connections. We need to create at least one (unless 0 are
566 // requested to be set) in order to allow the other side to reliably make
567 // any requests at all.
568
Steven Moreland4198a122021-08-03 17:37:58 -0700569 // we've already setup one client
Steven Morelande65f73c2023-03-04 01:34:50 +0000570 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing connections (server max: "
571 "%zu) and %zu incoming threads",
572 outgoingConnections, numThreadsAvailable, mMaxIncomingThreads);
573 for (size_t i = 0; i + 1 < outgoingConnections; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700574 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700575 }
576
Yifan Hong10423062021-10-08 16:26:32 -0700577 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700578 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000579 }
580
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +0000581 cleanup.release();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700582
Steven Moreland2372f9d2021-08-05 15:42:01 -0700583 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000584}
585
Steven Moreland2372f9d2021-08-05 15:42:01 -0700586status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700587 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700588 return setupOneSocketConnection(addr, sessionId, incoming);
589 });
590}
591
Steven Moreland2372f9d2021-08-05 15:42:01 -0700592status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700593 const std::vector<uint8_t>& sessionId,
594 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000595 for (size_t tries = 0; tries < 5; tries++) {
596 if (tries > 0) usleep(10000);
597
Yifan Hongb675ffe2021-08-05 16:37:17 -0700598 unique_fd serverFd(TEMP_FAILURE_RETRY(
599 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000600 if (serverFd == -1) {
601 int savedErrno = errno;
602 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
603 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700604 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000605 }
606
Steven Moreland12af6f72023-03-07 15:14:25 +0000607 if (addr.addr()->sa_family == AF_INET || addr.addr()->sa_family == AF_INET6) {
608 int noDelay = 1;
609 int result =
610 setsockopt(serverFd.get(), IPPROTO_TCP, TCP_NODELAY, &noDelay, sizeof(noDelay));
611 if (result < 0) {
612 int savedErrno = errno;
613 ALOGE("Could not set TCP_NODELAY on %s: %s", addr.toString().c_str(),
614 strerror(savedErrno));
615 return -savedErrno;
616 }
617 }
618
Pawan3e0061c2022-08-26 21:08:34 +0000619 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000620
621 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700622 int connErrno = errno;
623 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
624 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
625 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Pawan49d74cb2022-08-03 21:19:11 +0000626 status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700627 if (pollStatus != OK) {
628 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
629 statusToString(pollStatus).c_str());
630 return pollStatus;
631 }
632 // Set connErrno to the errno that connect() would have set if the fd were blocking.
633 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000634 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
635 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700636 if (ret == -1) {
637 int savedErrno = errno;
638 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
639 "(Original error from connect() is: %s)",
640 strerror(savedErrno), strerror(connErrno));
641 return -savedErrno;
642 }
643 // Retrieved the real connErrno as if connect() was called with a blocking socket
644 // fd. Continue checking connErrno.
645 }
646 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000647 ALOGW("Connection reset on %s", addr.toString().c_str());
648 continue;
649 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700650 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
651 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700652 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700653 strerror(connErrno));
654 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700655 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000656 }
Pawan49d74cb2022-08-03 21:19:11 +0000657 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
658 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700659
Pawan49d74cb2022-08-03 21:19:11 +0000660 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000661 }
662
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000663 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700664 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000665}
666
Pawan3e0061c2022-08-26 21:08:34 +0000667status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700668 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700669 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700670 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700671 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700672 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700673 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700674 }
675
676 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
677
Steven Moreland826367f2021-09-10 14:05:31 -0700678 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
679 ALOGE("Session ID too big %zu", sessionId.size());
680 return BAD_VALUE;
681 }
682
Steven Moreland4198a122021-08-03 17:37:58 -0700683 RpcConnectionHeader header{
684 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
685 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000686 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700687 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700688 };
Steven Moreland4198a122021-08-03 17:37:58 -0700689
Steven Moreland826367f2021-09-10 14:05:31 -0700690 if (incoming) {
691 header.options |= RPC_CONNECTION_OPTION_INCOMING;
692 }
Steven Moreland4198a122021-08-03 17:37:58 -0700693
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000694 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000695 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
696 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700697 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700698 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700699 statusToString(sendHeaderStatus).c_str());
700 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700701 }
702
Steven Moreland826367f2021-09-10 14:05:31 -0700703 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000704 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
705 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000706 auto sendSessionIdStatus =
707 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
708 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700709 if (sendSessionIdStatus != OK) {
710 ALOGE("Could not write session ID ('%s') to socket: %s",
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000711 HexString(sessionId.data(), sessionId.size()).c_str(),
Steven Moreland826367f2021-09-10 14:05:31 -0700712 statusToString(sendSessionIdStatus).c_str());
713 return sendSessionIdStatus;
714 }
715 }
716
Steven Moreland4198a122021-08-03 17:37:58 -0700717 LOG_RPC_DETAIL("Socket at client: header sent");
718
719 if (incoming) {
720 return addIncomingConnection(std::move(server));
721 } else {
722 return addOutgoingConnection(std::move(server), true /*init*/);
723 }
724}
725
Steven Moreland2372f9d2021-08-05 15:42:01 -0700726status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000727 RpcMutex mutex;
728 RpcConditionVariable joinCv;
729 RpcMutexUniqueLock lock(mutex);
730 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000731 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
732 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000733 thread = RpcMaybeThread([&]() {
734 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700735 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000736 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
737 sp<RpcSession> session = thiz;
738 session->preJoinThreadOwnership(std::move(thread));
739
740 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700741 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000742
743 ownershipTransferred = true;
744 threadLock.unlock();
745 joinCv.notify_one();
746 // do not use & vars below
747
748 RpcSession::join(std::move(session), std::move(setupResult));
749 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000750 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000751 joinCv.wait(lock, [&] { return ownershipTransferred; });
752 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700753 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000754}
755
Yifan Hong832521e2021-08-05 14:55:40 -0700756status_t RpcSession::initShutdownTrigger() {
757 // first client connection added, but setForServer not called, so
758 // initializaing for a client.
759 if (mShutdownTrigger == nullptr) {
760 mShutdownTrigger = FdTrigger::make();
761 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
762 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
763 }
764 return OK;
765}
766
Steven Moreland2372f9d2021-08-05 15:42:01 -0700767status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000768 sp<RpcConnection> connection = sp<RpcConnection>::make();
769 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000770 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700771 connection->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000772 connection->exclusiveTid = binder::os::GetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700773 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000774 }
775
Steven Morelandb86e26b2021-06-12 00:35:58 +0000776 status_t status = OK;
777 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700778 status =
779 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000780 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000781
Andrei Homescuc8490872022-06-23 05:18:51 +0000782 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000783
Steven Moreland2372f9d2021-08-05 15:42:01 -0700784 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000785}
786
Steven Morelanda8b44292021-06-08 01:27:53 +0000787bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700788 const std::vector<uint8_t>& sessionId,
789 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000790 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
791 LOG_ALWAYS_FATAL_IF(server == nullptr);
792 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
793 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000794 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000795 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000796
797 mShutdownTrigger = FdTrigger::make();
798 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000799
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000800 mId = sessionId;
801 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000802 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700803 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000804 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000805}
806
Yifan Hong702115c2021-06-24 15:39:18 -0700807sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
808 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000809 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700810
Yifan Hong10423062021-10-08 16:26:32 -0700811 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700812 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700813 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700814 return nullptr;
815 }
816
Steven Morelanddd67b942021-07-23 17:15:41 -0700817 // Don't accept any more connections, some have shutdown. Usually this
818 // happens when new connections are still being established as part of a
819 // very short-lived session which shuts down after it already started
820 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700821 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700822 return nullptr;
823 }
824
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000825 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700826 session->rpcTransport = std::move(rpcTransport);
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000827 session->exclusiveTid = binder::os::GetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700828
Steven Morelanda59937e2021-10-04 17:42:30 -0700829 mConnections.mIncoming.push_back(session);
830 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000831
832 return session;
833}
834
Steven Moreland19fc9f72021-06-10 03:57:30 +0000835bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000836 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700837 if (auto it =
838 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
839 it != mConnections.mIncoming.end()) {
840 mConnections.mIncoming.erase(it);
841 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000842 sp<EventListener> listener = mEventListener.promote();
843 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700844 _l.unlock();
845 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000846 }
Steven Morelandee78e762021-05-05 21:12:51 +0000847 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000848 return true;
849 }
850 return false;
851}
852
Andrei Homescuc8490872022-06-23 05:18:51 +0000853void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000854 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000855 connection->exclusiveTid = std::nullopt;
856 if (mConnections.mWaitingThreads > 0) {
857 _l.unlock();
858 mAvailableConnectionCv.notify_one();
859 }
860}
861
Yifan Hong9734cfc2021-09-13 16:14:09 -0700862std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700863 return mCtx->getCertificate(format);
864}
865
Steven Moreland195edb82021-06-08 02:44:39 +0000866status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
867 ExclusiveConnection* connection) {
868 connection->mSession = session;
869 connection->mConnection = nullptr;
870 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000871
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000872 uint64_t tid = binder::os::GetThreadId();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000873 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000874
Steven Morelanda59937e2021-10-04 17:42:30 -0700875 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000876 while (true) {
877 sp<RpcConnection> exclusive;
878 sp<RpcConnection> available;
879
880 // CHECK FOR DEDICATED CLIENT SOCKET
881 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000882 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700883 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
884 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000885
886 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700887 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000888 //
889 // Imagine we have more than one thread in play, and a single thread
890 // sends a synchronous, then an asynchronous command. Imagine the
891 // asynchronous command is sent on the first client connection. Then, if
892 // we naively send a synchronous command to that same connection, the
893 // thread on the far side might be busy processing the asynchronous
894 // command. So, we move to considering the second available thread
895 // for subsequent calls.
896 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700897 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
898 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000899 }
900
Steven Morelandc7d40132021-06-10 03:42:11 +0000901 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000902 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000903 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000904 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000905 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700906 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000907
908 // asynchronous calls cannot be nested, we currently allow ref count
909 // calls to be nested (so that you can use this without having extra
910 // threads). Note 'drainCommands' is used so that these ref counts can't
911 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000912 if (exclusiveIncoming != nullptr) {
913 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000914 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000915 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000916 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
917 // prefer available socket, but if we don't have one, don't
918 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000919 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000920 }
921 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000922 }
923
Steven Moreland85e067b2021-05-26 17:43:53 +0000924 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000925 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000926 connection->mConnection = exclusive;
927 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000928 break;
929 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000930 connection->mConnection = available;
931 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000932 break;
933 }
934
Steven Morelanda59937e2021-10-04 17:42:30 -0700935 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000936 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
937 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
938 "reason: %d. Incoming connections: %zu. %s.",
939 static_cast<int>(use), session->mConnections.mIncoming.size(),
940 (session->server()
941 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
942 "for the corresponding client"
Steven Morelandfeb13e82023-03-01 01:25:33 +0000943 : "This is a client session, so see "
944 "RpcSession::setMaxOutgoingConnections "
Steven Moreland25d9cc52022-03-10 23:11:56 +0000945 "for this client or RpcServer::setMaxThreads for the corresponding "
946 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000947 return WOULD_BLOCK;
948 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000949
Steven Moreland85e067b2021-05-26 17:43:53 +0000950 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700951 session->mConnections.mOutgoing.size(),
952 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000953 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000954 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700955 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000956
957 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000958}
959
Andrei Homescue922b232022-04-23 03:41:09 +0000960void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000961 sp<RpcConnection>* available,
962 std::vector<sp<RpcConnection>>& sockets,
963 size_t socketsIndexHint) {
964 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
965 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
966
967 if (*exclusive != nullptr) return; // consistent with break below
968
969 for (size_t i = 0; i < sockets.size(); i++) {
970 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
971
Steven Moreland85e067b2021-05-26 17:43:53 +0000972 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000973 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
974 *available = socket;
975 continue;
976 }
977
Steven Moreland85e067b2021-05-26 17:43:53 +0000978 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000979 // (nested transactions)
980 if (exclusive && socket->exclusiveTid == tid) {
981 *exclusive = socket;
982 break; // consistent with return above
983 }
984 }
985}
986
987RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000988 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000989 // is using this fd, and it retains the right to it. So, we don't give up
990 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000991 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000992 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000993 }
994}
995
Pawan1c24f9c2022-08-26 23:23:15 +0000996bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
997 for (const auto& connection : connections) {
998 if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
999 return true;
1000 }
1001 }
1002 return false;
1003}
1004
1005bool RpcSession::hasActiveRequests() {
1006 RpcMutexUniqueLock _l(mMutex);
1007 if (hasActiveConnection(mConnections.mIncoming)) {
1008 return true;
1009 }
1010 if (hasActiveConnection(mConnections.mOutgoing)) {
1011 return true;
1012 }
1013 return mConnections.mWaitingThreads != 0;
1014}
1015
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001016} // namespace android