blob: 3efd84f14598a26a34d8915abe7fb93fa98ba5ed [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +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
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000017#ifndef __ANDROID_VENDOR__
18// only used on NDK tests outside of vendor
Andrei Homescu9d8adb12022-08-02 04:38:30 +000019#include <aidl/IBinderRpcTest.h>
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000020#endif
Steven Moreland5553ac42020-11-11 02:14:45 +000021
Steven Morelandc1635952021-04-01 16:20:47 +000022#include <chrono>
23#include <cstdlib>
24#include <iostream>
25#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000026#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000027
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070028#include <dirent.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000029#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070030#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000031#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000032#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000033
Andrei Homescud65666d2023-03-03 07:28:02 +000034#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000035#include <binder/RpcTransportTipcAndroid.h>
36#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000037#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000038
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -080039#include "../Utils.h"
Andrei Homescu2a298012022-06-15 01:08:54 +000040#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000041#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000042
Yifan Hong1a235852021-05-13 16:07:47 -070043using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070044using namespace std::placeholders;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070045using android::binder::borrowed_fd;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -070046using android::binder::GetExecutableDirectory;
47using android::binder::ReadFdToString;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070048using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070049using testing::AssertionFailure;
50using testing::AssertionResult;
51using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070052
Steven Moreland5553ac42020-11-11 02:14:45 +000053namespace android {
54
Andrei Homescu12106de2022-04-27 04:42:21 +000055#ifdef BINDER_TEST_NO_SHARED_LIBS
56constexpr bool kEnableSharedLibs = false;
57#else
58constexpr bool kEnableSharedLibs = true;
59#endif
60
Andrei Homescud65666d2023-03-03 07:28:02 +000061#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000062constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
63#endif
64
Frederick Maylea12b0962022-06-25 01:13:22 +000065static std::string WaitStatusToString(int wstatus) {
66 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070067 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000068 }
69 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070070 return "term signal " + std::to_string(WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000071 }
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070072 return "unexpected state " + std::to_string(wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000073}
74
Steven Moreland276d8df2022-09-28 23:56:39 +000075static void debugBacktrace(pid_t pid) {
76 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
77 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
78}
79
Steven Moreland5553ac42020-11-11 02:14:45 +000080class Process {
81public:
Andrei Homescu96834632022-10-14 00:49:49 +000082 Process(Process&& other)
83 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
84 mReadEnd(std::move(other.mReadEnd)),
85 mWriteEnd(std::move(other.mWriteEnd)) {
86 // The default move constructor doesn't clear mPid after moving it,
87 // which we need to do because the destructor checks for mPid!=0
88 mPid = other.mPid;
89 other.mPid = 0;
90 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070091 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
92 unique_fd childWriteEnd;
93 unique_fd childReadEnd;
94 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
95 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +000096 if (0 == (mPid = fork())) {
97 // racey: assume parent doesn't crash before this is set
98 prctl(PR_SET_PDEATHSIG, SIGHUP);
99
Yifan Hong1deca4b2021-09-10 16:16:44 -0700100 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000101
102 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000103 }
104 }
105 ~Process() {
106 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000107 int wstatus;
108 waitpid(mPid, &wstatus, 0);
109 if (mCustomExitStatusCheck) {
110 mCustomExitStatusCheck(wstatus);
111 } else {
112 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
113 << "server process failed: " << WaitStatusToString(wstatus);
114 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000115 }
116 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700117 borrowed_fd readEnd() { return mReadEnd; }
118 borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000119
Frederick Maylea12b0962022-06-25 01:13:22 +0000120 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
121 mCustomExitStatusCheck = std::move(f);
122 }
123
Frederick Mayle69a0c992022-05-26 20:38:39 +0000124 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
125 void terminate() { kill(mPid, SIGTERM); }
126
Steven Moreland276d8df2022-09-28 23:56:39 +0000127 pid_t getPid() { return mPid; }
128
Steven Moreland5553ac42020-11-11 02:14:45 +0000129private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000130 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000131 pid_t mPid = 0;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700132 unique_fd mReadEnd;
133 unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000134};
135
136static std::string allocateSocketAddress() {
137 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000138 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000139 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700140 unlink(ret.c_str());
141 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000142};
143
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700144static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000145 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700146 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700147 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
148 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
149 PLOGF("initUnixSocket failed to bind");
150 }
Alice Wang893a9912022-10-24 10:44:09 +0000151 return fd;
152}
153
Andrei Homescu96834632022-10-14 00:49:49 +0000154// Destructors need to be defined, even if pure virtual
155ProcessSession::~ProcessSession() {}
156
157class LinuxProcessSession : public ProcessSession {
158public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000159 // reference to process hosting a socket server
160 Process host;
161
Andrei Homescu96834632022-10-14 00:49:49 +0000162 LinuxProcessSession(LinuxProcessSession&&) = default;
163 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
164 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165 for (auto& session : sessions) {
166 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000167 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000168
Steven Moreland67f85902023-03-15 01:13:49 +0000169 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
170 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 EXPECT_NE(nullptr, session);
174 EXPECT_NE(nullptr, session->state());
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700175 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000176
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 wp<RpcSession> weakSession = session;
178 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000179
Steven Moreland57042712022-10-04 23:56:45 +0000180 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
181 // the object should not actually be promotable. By looping, we distinguish a race here
182 // from a bug causing the object to not be promotable.
183 for (size_t i = 0; i < 3; i++) {
184 sp<RpcSession> strongSession = weakSession.promote();
185 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000186 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000187 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
188 "Leaked sess: ")
189 << strongSession->getStrongCount() << " checked time " << i;
190
191 if (strongSession != nullptr) {
192 sleep(1);
193 }
194 }
Steven Moreland736664b2021-05-01 04:27:25 +0000195 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000197
Andrei Homescu96834632022-10-14 00:49:49 +0000198 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
199 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000200 }
Andrei Homescu96834632022-10-14 00:49:49 +0000201
202 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000203};
204
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700205static unique_fd connectTo(const RpcSocketAddress& addr) {
206 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700207 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700208 if (!serverFd.ok()) {
209 PLOGF("Could not create socket %s", addr.toString().c_str());
210 }
Steven Moreland4198a122021-08-03 17:37:58 -0700211
212 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700213 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700214 }
215 return serverFd;
216}
217
Andrei Homescud65666d2023-03-03 07:28:02 +0000218#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700219static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
220 unique_fd sockClient, sockServer;
221 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700222 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100223 }
224
225 int zero = 0;
226 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700227 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100228 fds.emplace_back(std::move(sockServer));
229
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000230 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700231 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100232 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700233 return sockClient;
David Brazdil21c887c2022-09-23 12:25:18 +0100234}
Andrei Homescud65666d2023-03-03 07:28:02 +0000235#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100236
Andrei Homescuf30148c2023-03-10 00:31:45 +0000237std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
238 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000239}
Andrei Homescu2a298012022-06-15 01:08:54 +0000240
Andrei Homescu96834632022-10-14 00:49:49 +0000241// This creates a new process serving an interface on a certain number of
242// threads.
243std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
244 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700245 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000246
Steven Moreland67f85902023-03-15 01:13:49 +0000247 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700248 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
249 "%s: %zu != %zu", __func__,
250 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000251 }
252
Steven Morelandb469f432023-07-28 22:13:47 +0000253 SocketType socketType = GetParam().type;
254 RpcSecurity rpcSecurity = GetParam().security;
255 uint32_t clientVersion = GetParam().clientVersion;
256 uint32_t serverVersion = GetParam().serverVersion;
257 bool singleThreaded = GetParam().singleThreaded;
258 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000259
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700260 std::string path = GetExecutableDirectory();
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -0700261 auto servicePath = path + "/binder_rpc_test_service" +
262 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "");
Andrei Homescu96834632022-10-14 00:49:49 +0000263
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700264 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000265
Alice Wang893a9912022-10-24 10:44:09 +0000266 auto addr = allocateSocketAddress();
267 // Initializes the socket before the fork/exec.
268 if (socketType == SocketType::UNIX_RAW) {
269 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000270 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
271 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
272 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700273 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700274 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000275 }
Alice Wang893a9912022-10-24 10:44:09 +0000276 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000277
Andrei Homescu96834632022-10-14 00:49:49 +0000278 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700279 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000280 if (socketType == SocketType::TIPC) {
281 // Trusty has a single persistent service
282 return;
283 }
284
Andrei Homescu96834632022-10-14 00:49:49 +0000285 auto writeFd = std::to_string(writeEnd.get());
286 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800287 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
288 readFd.c_str(), NULL);
289 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
290 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000291 }));
292
293 BinderRpcTestServerConfig serverConfig;
294 serverConfig.numThreads = options.numThreads;
295 serverConfig.socketType = static_cast<int32_t>(socketType);
296 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
297 serverConfig.serverVersion = serverVersion;
Alice Wang893a9912022-10-24 10:44:09 +0000298 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000299 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000300 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
301 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
302 static_cast<int32_t>(mode));
303 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000304 if (socketType != SocketType::TIPC) {
305 writeToFd(ret->host.writeEnd(), serverConfig);
306 }
Andrei Homescu96834632022-10-14 00:49:49 +0000307
308 std::vector<sp<RpcSession>> sessions;
309 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
310 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 std::unique_ptr<RpcTransportCtxFactory> factory;
312 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000313#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000314 factory = RpcTransportCtxFactoryTipcAndroid::make();
315#else
316 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
317#endif
318 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000319 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000320 }
321 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100322 }
323
Andrei Homescu68a55612022-08-02 01:25:15 +0000324 BinderRpcTestServerInfo serverInfo;
325 if (socketType != SocketType::TIPC) {
326 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
327 BinderRpcTestClientInfo clientInfo;
328 for (const auto& session : sessions) {
329 auto& parcelableCert = clientInfo.certs.emplace_back();
330 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
331 }
332 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000333
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700334 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000335 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700336 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000337 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000338
Andrei Homescu68a55612022-08-02 01:25:15 +0000339 if (rpcSecurity == RpcSecurity::TLS) {
340 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700341 LOG_ALWAYS_FATAL_IF(
342 OK !=
343 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000344 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700345 }
346
Andrei Homescu96834632022-10-14 00:49:49 +0000347 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000348
Steven Moreland67f85902023-03-15 01:13:49 +0000349 for (size_t i = 0; i < sessions.size(); i++) {
350 const auto& session = sessions.at(i);
351
352 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
353 ? options.numIncomingConnectionsBySession.at(i)
354 : 0;
355
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700356 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000357 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000358 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000359 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000360
Andrei Homescu96834632022-10-14 00:49:49 +0000361 switch (socketType) {
362 case SocketType::PRECONNECTED:
363 status = session->setupPreconnectedClient({}, [=]() {
364 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
365 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 break;
Alice Wang893a9912022-10-24 10:44:09 +0000367 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000368 case SocketType::UNIX:
369 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
370 break;
371 case SocketType::UNIX_BOOTSTRAP:
372 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700373 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000374 break;
375 case SocketType::VSOCK:
Tomasz Wasilczyk022db682024-06-17 13:55:51 -0700376 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverInfo.port);
Andrei Homescu96834632022-10-14 00:49:49 +0000377 break;
378 case SocketType::INET:
379 status = session->setupInetClient("127.0.0.1", serverInfo.port);
380 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000381 case SocketType::TIPC:
382 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000383#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000384 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000385 for (size_t i = 0; i < 5; i++) {
386 // Try to connect several times,
387 // in case the service is slow to start
388 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
389 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700390 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000391 }
392 usleep(50000);
393 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700394 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000395#else
396 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700397 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000398#endif
399 });
400 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000401 default:
402 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000403 }
Andrei Homescu96834632022-10-14 00:49:49 +0000404 if (options.allowConnectFailure && status != OK) {
405 ret->sessions.clear();
406 break;
407 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700408 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Andrei Homescu96834632022-10-14 00:49:49 +0000409 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000410 }
Andrei Homescu96834632022-10-14 00:49:49 +0000411 return ret;
412}
Steven Morelandc1635952021-04-01 16:20:47 +0000413
Andrei Homescua858b0e2022-08-01 23:43:09 +0000414TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
415 if (clientOrServerSingleThreaded()) {
416 GTEST_SKIP() << "This test requires multiple threads";
417 }
418
Steven Moreland5553ac42020-11-11 02:14:45 +0000419 constexpr size_t kNumThreads = 10;
420
Steven Moreland4313d7e2021-07-15 23:41:22 +0000421 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000422
423 EXPECT_OK(proc.rootIface->lock());
424
425 // block all but one thread taking locks
426 std::vector<std::thread> ts;
427 for (size_t i = 0; i < kNumThreads - 1; i++) {
428 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
429 }
430
Steven Morelandd6d816f2022-12-23 01:37:17 +0000431 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000432
433 // other calls still work
434 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
435
Steven Morelandd6d816f2022-12-23 01:37:17 +0000436 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000437 size_t epochMsBefore = epochMillis();
438 // after this, we should never see a response within this time
439 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
440
441 // this call should be blocked for blockTimeMs
442 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
443
444 size_t epochMsAfter = epochMillis();
445 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
446
447 for (auto& t : ts) t.join();
448}
449
Steven Moreland27f620a2023-03-06 19:44:36 +0000450static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000451 size_t epochMsBefore = epochMillis();
452
453 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700454 for (size_t i = 0; i < numCalls; i++) {
455 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000456 }
457
458 for (auto& t : ts) t.join();
459
460 size_t epochMsAfter = epochMillis();
461
Yifan Hong1f44f982021-10-08 17:16:47 -0700462 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000463
Steven Moreland9c203222023-05-31 21:26:41 +0000464 // Potential flake, but make sure calls are handled in parallel. Due
465 // to past flakes, this only checks that the amount of time taken has
466 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
467 // check this more exactly.
468 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700469}
470
Andrei Homescua858b0e2022-08-01 23:43:09 +0000471TEST_P(BinderRpc, ThreadPoolOverSaturated) {
472 if (clientOrServerSingleThreaded()) {
473 GTEST_SKIP() << "This test requires multiple threads";
474 }
475
Yifan Hong1f44f982021-10-08 17:16:47 -0700476 constexpr size_t kNumThreads = 10;
477 constexpr size_t kNumCalls = kNumThreads + 3;
478 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000479
480 // b/272429574 - below 500ms, the test fails
481 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700482}
483
Andrei Homescua858b0e2022-08-01 23:43:09 +0000484TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
485 if (clientOrServerSingleThreaded()) {
486 GTEST_SKIP() << "This test requires multiple threads";
487 }
488
Yifan Hong1f44f982021-10-08 17:16:47 -0700489 constexpr size_t kNumThreads = 20;
490 constexpr size_t kNumOutgoingConnections = 10;
491 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
492 auto proc = createRpcTestSocketServerProcess(
493 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000494
495 // b/272429574 - below 500ms, the test fails
496 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000497}
498
Andrei Homescua858b0e2022-08-01 23:43:09 +0000499TEST_P(BinderRpc, ThreadingStressTest) {
500 if (clientOrServerSingleThreaded()) {
501 GTEST_SKIP() << "This test requires multiple threads";
502 }
503
Steven Moreland27f620a2023-03-06 19:44:36 +0000504 constexpr size_t kNumClientThreads = 5;
505 constexpr size_t kNumServerThreads = 5;
506 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000507
Steven Moreland4313d7e2021-07-15 23:41:22 +0000508 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000509
510 std::vector<std::thread> threads;
511 for (size_t i = 0; i < kNumClientThreads; i++) {
512 threads.push_back(std::thread([&] {
513 for (size_t j = 0; j < kNumCalls; j++) {
514 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000515 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000516 EXPECT_EQ(proc.rootBinder, out);
517 }
518 }));
519 }
520
521 for (auto& t : threads) t.join();
522}
523
Steven Moreland925ba0a2021-09-17 18:06:32 -0700524static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
525 std::vector<std::thread> threads;
526 for (size_t i = 0; i < threadCount; i++) {
527 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
528 }
529 for (auto& t : threads) t.join();
530}
531
Andrei Homescua858b0e2022-08-01 23:43:09 +0000532TEST_P(BinderRpc, OnewayStressTest) {
533 if (clientOrServerSingleThreaded()) {
534 GTEST_SKIP() << "This test requires multiple threads";
535 }
536
Steven Morelandc6046982021-04-20 00:49:42 +0000537 constexpr size_t kNumClientThreads = 10;
538 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700539 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000540
Steven Moreland4313d7e2021-07-15 23:41:22 +0000541 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000542
543 std::vector<std::thread> threads;
544 for (size_t i = 0; i < kNumClientThreads; i++) {
545 threads.push_back(std::thread([&] {
546 for (size_t j = 0; j < kNumCalls; j++) {
547 EXPECT_OK(proc.rootIface->sendString("a"));
548 }
Steven Morelandc6046982021-04-20 00:49:42 +0000549 }));
550 }
551
552 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700553
554 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000555}
556
Frederick Mayleb0221d12022-10-03 23:10:53 +0000557TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
558 if (!supportsFdTransport()) {
559 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
560 }
561 if (clientOrServerSingleThreaded()) {
562 GTEST_SKIP() << "This test requires multiple threads";
563 }
564
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000565 constexpr size_t kNumServerThreads = 3;
566
Frederick Mayleb0221d12022-10-03 23:10:53 +0000567 // This test forces a oneway transaction to be queued by issuing two
568 // `blockingSendFdOneway` calls, then drains the queue by issuing two
569 // `blockingRecvFd` calls.
570 //
571 // For more details about the queuing semantics see
572 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
573
574 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000575 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000576 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
577 .serverSupportedFileDescriptorTransportModes =
578 {RpcSession::FileDescriptorTransportMode::UNIX},
579 });
580
581 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
582 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
583 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
584 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
585
586 android::os::ParcelFileDescriptor fdA;
587 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
588 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700589 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000590 EXPECT_EQ(result, "a");
591
592 android::os::ParcelFileDescriptor fdB;
593 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700594 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000595 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000596
597 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000598}
599
Andrei Homescua858b0e2022-08-01 23:43:09 +0000600TEST_P(BinderRpc, OnewayCallQueueing) {
601 if (clientOrServerSingleThreaded()) {
602 GTEST_SKIP() << "This test requires multiple threads";
603 }
604
Frederick Mayle96872592023-03-07 14:56:15 -0800605 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000607
608 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000609 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000610
Frederick Mayle96872592023-03-07 14:56:15 -0800611 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700612 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800613 for (size_t i = 0; i + 1 < kNumQueued; i++) {
614 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 }
Frederick Mayle96872592023-03-07 14:56:15 -0800616 for (size_t i = 0; i + 1 < kNumQueued; i++) {
617 int n;
618 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700619 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800620 }
Steven Morelandf5174272021-05-25 00:39:28 +0000621
Steven Moreland925ba0a2021-09-17 18:06:32 -0700622 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000623}
624
Andrei Homescua858b0e2022-08-01 23:43:09 +0000625TEST_P(BinderRpc, OnewayCallExhaustion) {
626 if (clientOrServerSingleThreaded()) {
627 GTEST_SKIP() << "This test requires multiple threads";
628 }
629
Steven Morelandd45be622021-06-04 02:19:37 +0000630 constexpr size_t kNumClients = 2;
631 constexpr size_t kTooLongMs = 1000;
632
Steven Moreland4313d7e2021-07-15 23:41:22 +0000633 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000634
635 // Build up oneway calls on the second session to make sure it terminates
636 // and shuts down. The first session should be unaffected (proc destructor
637 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000638 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000639
640 std::vector<std::thread> threads;
641 for (size_t i = 0; i < kNumClients; i++) {
642 // one of these threads will get stuck queueing a transaction once the
643 // socket fills up, the other will be able to fill up transactions on
644 // this object
645 threads.push_back(std::thread([&] {
646 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
647 }
648 }));
649 }
650 for (auto& t : threads) t.join();
651
652 Status status = iface->sleepMsAsync(kTooLongMs);
653 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
654
Steven Moreland798e0d12021-07-14 23:19:25 +0000655 // now that it has died, wait for the remote session to shutdown
656 std::vector<int32_t> remoteCounts;
657 do {
658 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
659 } while (remoteCounts.size() == kNumClients);
660
Steven Morelandd45be622021-06-04 02:19:37 +0000661 // the second session should be shutdown in the other process by the time we
662 // are able to join above (it'll only be hung up once it finishes processing
663 // any pending commands). We need to erase this session from the record
664 // here, so that the destructor for our session won't check that this
665 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000666 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000667}
668
Steven Moreland67f85902023-03-15 01:13:49 +0000669TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
670 if (clientOrServerSingleThreaded()) {
671 GTEST_SKIP() << "This test requires multiple threads";
672 }
673
674 // session 0 - will check for leaks in destrutor of proc
675 // session 1 - we want to make sure it gets deleted when we drop all references to it
676 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700677 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000678
679 wp<RpcSession> session = proc.proc->sessions.at(1).session;
680
681 // remove all references to the second session
682 proc.proc->sessions.at(1).root = nullptr;
683 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
684
685 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
686 // to drain commands.
687 for (size_t i = 0; i < 100; i++) {
688 usleep(10 * 1000);
689 if (session.promote() == nullptr) break;
690 }
691
692 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000693
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000694 // now that it has died, wait for the remote session to shutdown
695 std::vector<int32_t> remoteCounts;
696 do {
697 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
698 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000699}
700
Devin Moore66d5b7a2022-07-07 21:42:10 +0000701TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000702 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000703 GTEST_SKIP() << "This test requires multiple threads";
704 }
705 class MyDeathRec : public IBinder::DeathRecipient {
706 public:
707 void binderDied(const wp<IBinder>& /* who */) override {
708 dead = true;
709 mCv.notify_one();
710 }
711 std::mutex mMtx;
712 std::condition_variable mCv;
713 bool dead = false;
714 };
715
716 // Death recipient needs to have an incoming connection to be called
717 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000718 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000719
720 auto dr = sp<MyDeathRec>::make();
721 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
722
723 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
724 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
725 }
726
727 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000728 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000729
730 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000731 // can't do this before checking the death recipient by calling
732 // forceShutdown earlier, because shutdownAndWait will also trigger
733 // a death recipient, but if we had a way to wait for the service
734 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000735 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000736 proc.expectAlreadyShutdown = true;
737}
738
739TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000740 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000741 GTEST_SKIP() << "This test requires multiple threads";
742 }
743 class MyDeathRec : public IBinder::DeathRecipient {
744 public:
745 void binderDied(const wp<IBinder>& /* who */) override {
746 dead = true;
747 mCv.notify_one();
748 }
749 std::mutex mMtx;
750 std::condition_variable mCv;
751 bool dead = false;
752 };
753
754 // Death recipient needs to have an incoming connection to be called
755 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000756 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000757
758 auto dr = sp<MyDeathRec>::make();
759 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
760
761 // Explicitly calling shutDownAndWait will cause the death recipients
762 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000763 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000764
765 std::unique_lock<std::mutex> lock(dr->mMtx);
766 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000767 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000768 }
769 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
770
Andrei Homescu96834632022-10-14 00:49:49 +0000771 proc.proc->terminate();
772 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000773 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
774 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
775 });
776 proc.expectAlreadyShutdown = true;
777}
778
Steven Moreland5ec743f2023-01-18 01:02:06 +0000779TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000780 if (socketType() == SocketType::TIPC) {
781 // This should work, but Trusty takes too long to restart the service
782 GTEST_SKIP() << "Service death test not supported on Trusty";
783 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000784 class MyDeathRec : public IBinder::DeathRecipient {
785 public:
786 void binderDied(const wp<IBinder>& /* who */) override {}
787 };
788
Steven Moreland67f85902023-03-15 01:13:49 +0000789 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000790
791 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000792 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000793}
794
795TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000796 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000797 GTEST_SKIP() << "This test requires multiple threads";
798 }
799 class MyDeathRec : public IBinder::DeathRecipient {
800 public:
801 void binderDied(const wp<IBinder>& /* who */) override {
802 GTEST_FAIL() << "This should not be called after unlinkToDeath";
803 }
804 };
805
806 // Death recipient needs to have an incoming connection to be called
807 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000808 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000809
810 auto dr = sp<MyDeathRec>::make();
811 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
812 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
813
Steven Moreland67f85902023-03-15 01:13:49 +0000814 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000815}
816
Steven Morelandc1635952021-04-01 16:20:47 +0000817TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000818 if (socketType() == SocketType::TIPC) {
819 // This should work, but Trusty takes too long to restart the service
820 GTEST_SKIP() << "Service death test not supported on Trusty";
821 }
822
Steven Moreland5553ac42020-11-11 02:14:45 +0000823 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000824 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000825
826 // make sure there is some state during crash
827 // 1. we hold their binder
828 sp<IBinderRpcSession> session;
829 EXPECT_OK(proc.rootIface->openSession("happy", &session));
830 // 2. they hold our binder
831 sp<IBinder> binder = new BBinder();
832 EXPECT_OK(proc.rootIface->holdBinder(binder));
833
834 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
835 << "Do death cleanup: " << doDeathCleanup;
836
Andrei Homescu96834632022-10-14 00:49:49 +0000837 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000838 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
839 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
840 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000841 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000842 }
843}
844
Steven Morelandd7302072021-05-15 01:32:04 +0000845TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000846 // This test only works if the current process shared the internal state of
847 // ProcessState with the service across the call to fork(). Both the static
848 // libraries and libbinder.so have their own separate copies of all the
849 // globals, so the test only works when the test client and service both use
850 // libbinder.so (when using static libraries, even a client and service
851 // using the same kind of static library should have separate copies of the
852 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000853 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000854 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
855 "at build time.";
856 }
857
Steven Moreland4313d7e2021-07-15 23:41:22 +0000858 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000859
Andrei Homescu2a298012022-06-15 01:08:54 +0000860 // we can't allocate IPCThreadState so actually the first time should
861 // succeed :(
862 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000863
864 // second time! we catch the error :)
865 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
866
Andrei Homescu96834632022-10-14 00:49:49 +0000867 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000868 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
869 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
870 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000871 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000872}
873
Frederick Mayle69a0c992022-05-26 20:38:39 +0000874TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000875 if (socketType() == SocketType::TIPC) {
876 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
877 }
878
Frederick Mayle69a0c992022-05-26 20:38:39 +0000879 auto proc = createRpcTestSocketServerProcess({
880 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
881 .serverSupportedFileDescriptorTransportModes =
882 {RpcSession::FileDescriptorTransportMode::UNIX},
883 .allowConnectFailure = true,
884 });
Andrei Homescu96834632022-10-14 00:49:49 +0000885 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
886 proc.proc->terminate();
887 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000888 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
889 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
890 });
891 proc.expectAlreadyShutdown = true;
892}
893
894TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000895 if (socketType() == SocketType::TIPC) {
896 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
897 }
898
Frederick Mayle69a0c992022-05-26 20:38:39 +0000899 auto proc = createRpcTestSocketServerProcess({
900 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
901 .serverSupportedFileDescriptorTransportModes =
902 {RpcSession::FileDescriptorTransportMode::NONE},
903 .allowConnectFailure = true,
904 });
Andrei Homescu96834632022-10-14 00:49:49 +0000905 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
906 proc.proc->terminate();
907 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000908 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
909 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
910 });
911 proc.expectAlreadyShutdown = true;
912}
913
914TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000915 if (socketType() == SocketType::TIPC) {
916 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
917 }
918
Frederick Mayle69a0c992022-05-26 20:38:39 +0000919 auto proc = createRpcTestSocketServerProcess({
920 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
921 .serverSupportedFileDescriptorTransportModes =
922 {RpcSession::FileDescriptorTransportMode::NONE,
923 RpcSession::FileDescriptorTransportMode::UNIX},
924 });
925
926 android::os::ParcelFileDescriptor out;
927 auto status = proc.rootIface->echoAsFile("hello", &out);
928 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
929}
930
931TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000932 if (socketType() == SocketType::TIPC) {
933 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
934 }
935
Frederick Mayle69a0c992022-05-26 20:38:39 +0000936 auto proc = createRpcTestSocketServerProcess({
937 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
938 .serverSupportedFileDescriptorTransportModes =
939 {RpcSession::FileDescriptorTransportMode::UNIX},
940 });
941
942 android::os::ParcelFileDescriptor out;
943 auto status = proc.rootIface->echoAsFile("hello", &out);
944 if (!supportsFdTransport()) {
945 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
946 return;
947 }
948 ASSERT_TRUE(status.isOk()) << status;
949
950 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700951 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700952 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000953}
954
955TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000956 if (socketType() == SocketType::TIPC) {
957 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
958 }
959
Frederick Mayle69a0c992022-05-26 20:38:39 +0000960 auto proc = createRpcTestSocketServerProcess({
961 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
962 .serverSupportedFileDescriptorTransportModes =
963 {RpcSession::FileDescriptorTransportMode::UNIX},
964 });
965
966 std::vector<android::os::ParcelFileDescriptor> files;
967 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
968 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
969 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
970 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
971
972 android::os::ParcelFileDescriptor out;
973 auto status = proc.rootIface->concatFiles(files, &out);
974 if (!supportsFdTransport()) {
975 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
976 return;
977 }
978 ASSERT_TRUE(status.isOk()) << status;
979
980 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700981 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000982 EXPECT_EQ(result, "123abcd");
983}
984
985TEST_P(BinderRpc, SendMaxFiles) {
986 if (!supportsFdTransport()) {
987 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
988 }
989
990 auto proc = createRpcTestSocketServerProcess({
991 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
992 .serverSupportedFileDescriptorTransportModes =
993 {RpcSession::FileDescriptorTransportMode::UNIX},
994 });
995
996 std::vector<android::os::ParcelFileDescriptor> files;
997 for (int i = 0; i < 253; i++) {
998 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
999 }
1000
1001 android::os::ParcelFileDescriptor out;
1002 auto status = proc.rootIface->concatFiles(files, &out);
1003 ASSERT_TRUE(status.isOk()) << status;
1004
1005 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001006 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001007 EXPECT_EQ(result, std::string(253, 'a'));
1008}
1009
1010TEST_P(BinderRpc, SendTooManyFiles) {
1011 if (!supportsFdTransport()) {
1012 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1013 }
1014
1015 auto proc = createRpcTestSocketServerProcess({
1016 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1017 .serverSupportedFileDescriptorTransportModes =
1018 {RpcSession::FileDescriptorTransportMode::UNIX},
1019 });
1020
1021 std::vector<android::os::ParcelFileDescriptor> files;
1022 for (int i = 0; i < 254; i++) {
1023 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1024 }
1025
1026 android::os::ParcelFileDescriptor out;
1027 auto status = proc.rootIface->concatFiles(files, &out);
1028 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1029}
1030
Andrei Homescufc221502022-10-08 03:51:17 +00001031TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001032 if (socketType() == SocketType::TIPC) {
1033 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1034 }
1035
Andrei Homescufc221502022-10-08 03:51:17 +00001036 auto proc = createRpcTestSocketServerProcess({
1037 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1038 .serverSupportedFileDescriptorTransportModes =
1039 {RpcSession::FileDescriptorTransportMode::UNIX},
1040 });
1041
1042 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1043 ASSERT_NE(badFd, -1);
1044
1045 // Close the file descriptor so it becomes invalid for dup
1046 close(badFd);
1047
1048 Parcel p1;
1049 p1.markForBinder(proc.rootBinder);
1050 p1.writeInt32(3);
1051 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1052
1053 Parcel pRaw;
1054 pRaw.markForBinder(proc.rootBinder);
1055 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1056
1057 pRaw.setDataPosition(0);
1058 EXPECT_EQ(3, pRaw.readInt32());
1059 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1060}
1061
Andrei Homescu68a55612022-08-02 01:25:15 +00001062#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001063TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001064 if constexpr (!kEnableSharedLibs) {
1065 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1066 }
1067
Steven Moreland4313d7e2021-07-15 23:41:22 +00001068 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001069
1070 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1071 ASSERT_NE(binder, nullptr);
1072
1073 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1074}
1075
1076TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001077 if constexpr (!kEnableSharedLibs) {
1078 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1079 }
1080
Steven Moreland4313d7e2021-07-15 23:41:22 +00001081 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001082
1083 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1084 ASSERT_NE(binder, nullptr);
1085
1086 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1087 ASSERT_NE(ndkBinder, nullptr);
1088
1089 std::string out;
1090 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1091 ASSERT_TRUE(status.isOk()) << status.getDescription();
1092 ASSERT_EQ("aoeuaoeu", out);
1093}
Andrei Homescu68a55612022-08-02 01:25:15 +00001094#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001095
Steven Moreland5553ac42020-11-11 02:14:45 +00001096ssize_t countFds() {
1097 DIR* dir = opendir("/proc/self/fd/");
1098 if (dir == nullptr) return -1;
1099 ssize_t ret = 0;
1100 dirent* ent;
1101 while ((ent = readdir(dir)) != nullptr) ret++;
1102 closedir(dir);
1103 return ret;
1104}
1105
Andrei Homescua858b0e2022-08-01 23:43:09 +00001106TEST_P(BinderRpc, Fds) {
1107 if (serverSingleThreaded()) {
1108 GTEST_SKIP() << "This test requires multiple threads";
1109 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001110 if (socketType() == SocketType::TIPC) {
1111 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1112 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001113
Steven Moreland5553ac42020-11-11 02:14:45 +00001114 ssize_t beforeFds = countFds();
1115 ASSERT_GE(beforeFds, 0);
1116 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001117 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001118 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1119 }
1120 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1121}
1122
Andrei Homescud65666d2023-03-03 07:28:02 +00001123#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001124
1125static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1126 std::vector<BinderRpc::ParamType> ret;
1127
1128 for (const auto& clientVersion : testVersions()) {
1129 for (const auto& serverVersion : testVersions()) {
1130 ret.push_back(BinderRpc::ParamType{
1131 .type = SocketType::TIPC,
1132 .security = RpcSecurity::RAW,
1133 .clientVersion = clientVersion,
1134 .serverVersion = serverVersion,
1135 .singleThreaded = true,
1136 .noKernel = true,
1137 });
1138 }
1139 }
1140
1141 return ret;
1142}
1143
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001144INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1145 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001146#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001147bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001148 // We don't need to enable TLS to know if vsock is supported.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001149 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001150 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001151
1152 if (errno == EAFNOSUPPORT) {
1153 return false;
1154 }
1155
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001156 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001157
1158 sockaddr_vm serverAddr{
1159 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001160 .svm_port = VMADDR_PORT_ANY,
Andrei Homescu992a4052022-06-28 21:26:18 +00001161 .svm_cid = VMADDR_CID_ANY,
1162 };
1163 int ret = TEMP_FAILURE_RETRY(
1164 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001165 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
Andrei Homescu992a4052022-06-28 21:26:18 +00001166 strerror(errno));
1167
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001168 socklen_t len = sizeof(serverAddr);
1169 ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
1170 LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
Hannah.Hsu6b1036f2024-07-09 11:20:20 +08001171 LOG_ALWAYS_FATAL_IF(len < static_cast<socklen_t>(sizeof(serverAddr)),
1172 "getsockname didn't read the full addr struct");
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001173
Andrei Homescu992a4052022-06-28 21:26:18 +00001174 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001175 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001176 strerror(errno));
1177
1178 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1179 // to see if the kernel supports it. It's safe to use a blocking
1180 // connect because vsock sockets have a 2 second connection timeout,
1181 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001182 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001183 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001184 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
1185 serverAddr.svm_port, strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001186
1187 bool success = false;
1188 sockaddr_vm connectAddr{
1189 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001190 .svm_port = serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001191 .svm_cid = VMADDR_CID_LOCAL,
1192 };
1193 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1194 sizeof(connectAddr)));
1195 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001196 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001197 while (true) {
1198 pollfd pfd[]{
1199 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1200 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1201 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001202 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001203 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1204
1205 if (pfd[0].revents & POLLIN) {
1206 sockaddr_vm acceptAddr;
1207 socklen_t acceptAddrLen = sizeof(acceptAddr);
1208 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1209 reinterpret_cast<sockaddr*>(&acceptAddr),
1210 &acceptAddrLen, SOCK_CLOEXEC));
1211 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1212 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1213 "Truncated address");
1214
1215 // Store the fd in acceptFd so we keep the connection alive
1216 // while polling connectFd
1217 acceptFd.reset(ret);
1218 }
1219
1220 if (pfd[1].revents & POLLOUT) {
1221 // Connect either succeeded or timed out
1222 int connectErrno;
1223 socklen_t connectErrnoLen = sizeof(connectErrno);
1224 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1225 &connectErrnoLen);
1226 LOG_ALWAYS_FATAL_IF(ret == -1,
1227 "Could not getsockopt() after connect() "
1228 "on non-blocking socket: %s.",
1229 strerror(errno));
1230
1231 // We're done, this is all we wanted
1232 success = connectErrno == 0;
1233 break;
1234 }
1235 }
1236 } else {
1237 success = ret == 0;
1238 }
1239
1240 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1241
1242 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001243}
1244
Yifan Hong1deca4b2021-09-10 16:16:44 -07001245static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001246 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1247 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001248
1249 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001250
Steven Moreland9f250b02023-05-16 23:27:42 +00001251#ifdef __BIONIC__
1252 // Devices may not have vsock support. AVF tests will verify whether they do, but
1253 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001254 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001255#else
1256 // On host machines, we always assume we have vsock loopback. If we don't, the
1257 // subsequent failures will be more clear than showing one now.
1258 static bool hasVsockLoopback = true;
1259#endif
Steven Morelandda573042021-06-12 01:13:45 +00001260
1261 if (hasVsockLoopback) {
1262 ret.push_back(SocketType::VSOCK);
1263 }
1264
1265 return ret;
1266}
1267
Steven Morelandb469f432023-07-28 22:13:47 +00001268static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1269 std::vector<BinderRpc::ParamType> ret;
1270
Steven Morelandf7421432023-07-28 22:41:44 +00001271 constexpr bool full = false;
1272
Steven Morelandb469f432023-07-28 22:13:47 +00001273 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001274 if (full || type == SocketType::UNIX) {
1275 for (const auto& security : RpcSecurityValues()) {
1276 for (const auto& clientVersion : testVersions()) {
1277 for (const auto& serverVersion : testVersions()) {
1278 for (bool singleThreaded : {false, true}) {
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001279 for (bool noKernel : noKernelValues()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001280 ret.push_back(BinderRpc::ParamType{
1281 .type = type,
1282 .security = security,
1283 .clientVersion = clientVersion,
1284 .serverVersion = serverVersion,
1285 .singleThreaded = singleThreaded,
1286 .noKernel = noKernel,
1287 });
1288 }
Steven Morelandb469f432023-07-28 22:13:47 +00001289 }
1290 }
1291 }
1292 }
Steven Morelandf7421432023-07-28 22:41:44 +00001293 } else {
1294 ret.push_back(BinderRpc::ParamType{
1295 .type = type,
1296 .security = RpcSecurity::RAW,
1297 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1298 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1299 .singleThreaded = false,
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001300 .noKernel = !kEnableKernelIpcTesting,
Steven Morelandf7421432023-07-28 22:41:44 +00001301 });
Steven Morelandb469f432023-07-28 22:13:47 +00001302 }
1303 }
Steven Morelandf7421432023-07-28 22:41:44 +00001304
Steven Morelandb469f432023-07-28 22:13:47 +00001305 return ret;
1306}
1307
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001308INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1309 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001310
Yifan Hong702115c2021-06-24 15:39:18 -07001311class BinderRpcServerRootObject
1312 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001313
1314TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1315 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1316 auto setRootObject = [](bool isStrong) -> SetFn {
1317 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1318 };
1319
Yifan Hong702115c2021-06-24 15:39:18 -07001320 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001321 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001322 auto binder1 = sp<BBinder>::make();
1323 IBinder* binderRaw1 = binder1.get();
1324 setRootObject(isStrong1)(server.get(), binder1);
1325 EXPECT_EQ(binderRaw1, server->getRootObject());
1326 binder1.clear();
1327 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1328
1329 auto binder2 = sp<BBinder>::make();
1330 IBinder* binderRaw2 = binder2.get();
1331 setRootObject(isStrong2)(server.get(), binder2);
1332 EXPECT_EQ(binderRaw2, server->getRootObject());
1333 binder2.clear();
1334 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1335}
1336
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001337INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1338 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1339 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001340
Yifan Hong1a235852021-05-13 16:07:47 -07001341class OneOffSignal {
1342public:
1343 // If notify() was previously called, or is called within |duration|, return true; else false.
1344 template <typename R, typename P>
1345 bool wait(std::chrono::duration<R, P> duration) {
1346 std::unique_lock<std::mutex> lock(mMutex);
1347 return mCv.wait_for(lock, duration, [this] { return mValue; });
1348 }
1349 void notify() {
1350 std::unique_lock<std::mutex> lock(mMutex);
1351 mValue = true;
1352 lock.unlock();
1353 mCv.notify_all();
1354 }
1355
1356private:
1357 std::mutex mMutex;
1358 std::condition_variable mCv;
1359 bool mValue = false;
1360};
1361
Yifan Hong194acf22021-06-29 18:44:56 -07001362TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001363 bool expectDebuggable = false;
1364#if defined(__ANDROID__)
1365 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1366 android::base::GetProperty("ro.build.type", "") != "user";
1367#else
Yifan Hong194acf22021-06-29 18:44:56 -07001368 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1369 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1370 "to binderHostDeviceTest. Hence, just disable this test on host.";
1371#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001372 if constexpr (!kEnableKernelIpc) {
1373 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1374 "at build time.";
1375 }
1376
Yifan Hong194acf22021-06-29 18:44:56 -07001377 sp<IServiceManager> sm = defaultServiceManager();
1378 ASSERT_NE(nullptr, sm);
1379 // Any Java service with non-empty getInterfaceDescriptor() would do.
1380 // Let's pick batteryproperties.
1381 auto binder = sm->checkService(String16("batteryproperties"));
1382 ASSERT_NE(nullptr, binder);
1383 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001384 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001385 ASSERT_EQ(OK, binder->pingBinder());
1386
1387 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001388 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001389 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001390 auto socket = rpcServer->releaseServer();
1391
1392 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001393 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1394
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001395 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001396 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001397 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1398 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001399 << statusToString(setRpcClientDebugStatus);
1400 GTEST_SKIP();
1401 }
1402
1403 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001404
1405 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001406 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001407 auto rpcBinder = rpcSession->getRootObject();
1408 ASSERT_NE(nullptr, rpcBinder);
1409
1410 ASSERT_EQ(OK, rpcBinder->pingBinder());
1411
1412 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1413 << "getInterfaceDescriptor should not crash system_server";
1414 ASSERT_EQ(OK, rpcBinder->pingBinder());
1415}
1416
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001417class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1418public:
1419 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001420 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001421 std::to_string(std::get<1>(info.param));
1422 }
1423};
1424
1425TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001426 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001427 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001428 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001429 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001430 ASSERT_FALSE(server->hasServer());
1431 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1432 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001433 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001434 ASSERT_FALSE(server->hasServer());
1435 ASSERT_EQ(sinkFd, retrieved.get());
1436}
1437
1438TEST_P(BinderRpcServerOnly, Shutdown) {
1439 if constexpr (!kEnableRpcThreads) {
1440 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1441 }
1442
1443 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001444 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001445 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001446 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1447 auto joinEnds = std::make_shared<OneOffSignal>();
1448
1449 // If things are broken and the thread never stops, don't block other tests. Because the thread
1450 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1451 // shared pointers are passed.
1452 std::thread([server, joinEnds] {
1453 server->join();
1454 joinEnds->notify();
1455 }).detach();
1456
1457 bool shutdown = false;
1458 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001459 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001460 if (server->shutdown()) shutdown = true;
1461 }
1462 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1463
1464 ASSERT_TRUE(joinEnds->wait(2s))
1465 << "After server->shutdown() returns true, join() did not stop after 2s";
1466}
1467
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001468INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1469 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1470 ::testing::ValuesIn(testVersions())),
1471 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001472
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001473class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001474public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001475 // Only parameterized only server version because `RpcSession` is bypassed
1476 // in the client half of the tests.
1477 using Param =
1478 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001479 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001480
1481 // A server that handles client socket connections.
1482 class Server {
1483 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001484 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001485
Yifan Hong1deca4b2021-09-10 16:16:44 -07001486 explicit Server() {}
1487 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001488 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001489 [[nodiscard]] AssertionResult setUp(
1490 const Param& param,
1491 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001492 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001493 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001494 if (!rpcServer->setProtocolVersion(serverVersion)) {
1495 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1496 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001497 switch (socketType) {
1498 case SocketType::PRECONNECTED: {
1499 return AssertionFailure() << "Not supported by this test";
1500 } break;
1501 case SocketType::UNIX: {
1502 auto addr = allocateSocketAddress();
1503 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1504 if (status != OK) {
1505 return AssertionFailure()
1506 << "setupUnixDomainServer: " << statusToString(status);
1507 }
1508 mConnectToServer = [addr] {
1509 return connectTo(UnixSocketAddress(addr.c_str()));
1510 };
1511 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001512 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001513 unique_fd bootstrapFdClient, bootstrapFdServer;
1514 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001515 return AssertionFailure() << "Socketpair() failed";
1516 }
1517 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1518 std::move(bootstrapFdServer));
1519 if (status != OK) {
1520 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1521 << statusToString(status);
1522 }
1523 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1524 mAcceptConnection = &Server::recvmsgServerConnection;
1525 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1526 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001527 case SocketType::UNIX_RAW: {
1528 auto addr = allocateSocketAddress();
1529 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1530 if (status != OK) {
1531 return AssertionFailure()
1532 << "setupRawSocketServer: " << statusToString(status);
1533 }
1534 mConnectToServer = [addr] {
1535 return connectTo(UnixSocketAddress(addr.c_str()));
1536 };
1537 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001538 case SocketType::VSOCK: {
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001539 unsigned port;
1540 auto status =
1541 rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001542 if (status != OK) {
1543 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1544 }
1545 mConnectToServer = [port] {
1546 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1547 };
1548 } break;
1549 case SocketType::INET: {
1550 unsigned int port;
1551 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1552 if (status != OK) {
1553 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1554 }
1555 mConnectToServer = [port] {
1556 const char* addr = kLocalInetAddress;
1557 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001558 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001559 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1560 auto fd = connectTo(
1561 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1562 if (fd.ok()) return fd;
1563 }
1564 ALOGE("None of the socket address resolved for %s:%u can be connected",
1565 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001566 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001567 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001568 } break;
1569 case SocketType::TIPC: {
1570 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1571 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001572 }
1573 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001574 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001575 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001576 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1577 mSetup = true;
1578 return AssertionSuccess();
1579 }
1580 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1581 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1582 return mCertVerifier;
1583 }
1584 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1585 void start() {
1586 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1587 mThread = std::make_unique<std::thread>(&Server::run, this);
1588 }
David Brazdil21c887c2022-09-23 12:25:18 +01001589
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001590 unique_fd acceptServerConnection() {
1591 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001592 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1593 }
1594
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001595 unique_fd recvmsgServerConnection() {
1596 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001597 int buf;
1598 iovec iov{&buf, sizeof(buf)};
1599
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001600 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001601 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001602 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001603 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1604 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001605 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001606 }
1607
Yifan Hong1deca4b2021-09-10 16:16:44 -07001608 void run() {
1609 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1610
1611 std::vector<std::thread> threads;
1612 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001613 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001614 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1615 }
1616
1617 for (auto& thread : threads) thread.join();
1618 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001619 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001621 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001622 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001624 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625 }
Yifan Honge07d2732021-09-13 21:59:14 -07001626 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001627 shutdown();
1628 join();
1629 }
1630 void shutdown() { mFdTrigger->trigger(); }
1631
1632 void setPostConnect(
1633 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1634 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001635 }
1636
1637 private:
1638 std::unique_ptr<std::thread> mThread;
1639 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001640 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001641 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001642 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001643 std::unique_ptr<RpcTransportCtx> mCtx;
1644 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1645 std::make_shared<RpcCertificateVerifierSimple>();
1646 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001647 // The function invoked after connection and handshake. By default, it is
1648 // |defaultPostConnect| that sends |kMessage| to the client.
1649 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1650 Server::defaultPostConnect;
1651
1652 void join() {
1653 if (mThread != nullptr) {
1654 mThread->join();
1655 mThread = nullptr;
1656 }
1657 }
1658
1659 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1660 FdTrigger* fdTrigger) {
1661 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001662 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001663 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001664 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001665 if (status != OK) return AssertionFailure() << statusToString(status);
1666 return AssertionSuccess();
1667 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001668 };
1669
1670 class Client {
1671 public:
1672 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1673 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001674 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001675 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1676 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001677 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001678 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001679 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1680 return AssertionSuccess();
1681 }
1682 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1683 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1684 return mCertVerifier;
1685 }
Yifan Hong67519322021-09-13 18:51:16 -07001686 // connect() and do handshake
1687 bool setUpTransport() {
1688 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001689 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001690 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1691 return mClientTransport != nullptr;
1692 }
1693 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1694 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1695 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001696 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001697 status_t readStatus =
1698 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001699 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001700 if (readStatus != OK) {
1701 return AssertionFailure() << statusToString(readStatus);
1702 }
1703 if (readMessage != expectedMessage) {
1704 return AssertionFailure()
1705 << "Expected " << expectedMessage << ", actual " << readMessage;
1706 }
1707 return AssertionSuccess();
1708 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001709 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001710 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001711 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1712 return;
1713 }
1714 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001715 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 }
1717
Pawan49d74cb2022-08-03 21:19:11 +00001718 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1719
Yifan Hong1deca4b2021-09-10 16:16:44 -07001720 private:
1721 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001722 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1724 std::unique_ptr<RpcTransportCtx> mCtx;
1725 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1726 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001727 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001728 };
1729
1730 // Make A trust B.
1731 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001732 static status_t trust(RpcSecurity rpcSecurity,
1733 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1734 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001736 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1737 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1738 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739 }
1740
1741 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001742};
1743
1744class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1745public:
1746 using Server = RpcTransportTestUtils::Server;
1747 using Client = RpcTransportTestUtils::Client;
1748 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001749 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001750 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001751 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001752 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753 return ret;
1754 }
1755 static std::vector<ParamType> getRpcTranportTestParams() {
1756 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001757 for (auto serverVersion : testVersions()) {
1758 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1759 for (auto rpcSecurity : RpcSecurityValues()) {
1760 switch (rpcSecurity) {
1761 case RpcSecurity::RAW: {
1762 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1763 } break;
1764 case RpcSecurity::TLS: {
1765 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1766 serverVersion);
1767 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1768 serverVersion);
1769 } break;
1770 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001771 }
1772 }
1773 }
1774 return ret;
1775 }
1776 template <typename A, typename B>
1777 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001778 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1779 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001780 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1781 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001782 void SetUp() override {
1783 if constexpr (!kEnableRpcThreads) {
1784 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1785 }
1786 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787};
1788
1789TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 auto server = std::make_unique<Server>();
1791 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001792
1793 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001794 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001795
1796 ASSERT_EQ(OK, trust(&client, server));
1797 ASSERT_EQ(OK, trust(server, &client));
1798
1799 server->start();
1800 client.run();
1801}
1802
1803TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001804 auto server = std::make_unique<Server>();
1805 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001806
1807 std::vector<Client> clients;
1808 for (int i = 0; i < 2; i++) {
1809 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001810 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001811 ASSERT_EQ(OK, trust(&client, server));
1812 ASSERT_EQ(OK, trust(server, &client));
1813 }
1814
1815 server->start();
1816 for (auto& client : clients) client.run();
1817}
1818
1819TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001820 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1821 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001822
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001823 auto untrustedServer = std::make_unique<Server>();
1824 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001825
1826 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001827 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001828
1829 ASSERT_EQ(OK, trust(untrustedServer, &client));
1830
1831 untrustedServer->start();
1832
1833 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1834 // the client can't verify the server's identity.
1835 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1836 client.run(handshakeOk);
1837}
1838TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001839 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1840 (void)serverVersion;
1841
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001842 auto validServer = std::make_unique<Server>();
1843 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001845 auto maliciousServer = std::make_unique<Server>();
1846 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001847
1848 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001850
1851 ASSERT_EQ(OK, trust(&client, validServer));
1852 ASSERT_EQ(OK, trust(validServer, &client));
1853 ASSERT_EQ(OK, trust(maliciousServer, &client));
1854
1855 maliciousServer->start();
1856
1857 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1858 // the client can't verify the server's identity.
1859 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1860 client.run(handshakeOk);
1861}
1862
1863TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001864 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1865 (void)serverVersion;
1866
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 auto server = std::make_unique<Server>();
1868 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869
1870 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001871 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001872
1873 ASSERT_EQ(OK, trust(&client, server));
1874
1875 server->start();
1876
1877 // For TLS, Client should be able to verify server's identity, so client should see
1878 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1879 // identity and should drop the connection, so client shouldn't be able to read anything.
1880 bool readOk = rpcSecurity != RpcSecurity::TLS;
1881 client.run(true, readOk);
1882}
1883
1884TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001885 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1886 (void)serverVersion;
1887
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001888 auto server = std::make_unique<Server>();
1889 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001890
1891 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001892 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001893 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001894 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895
1896 ASSERT_EQ(OK, trust(&validClient, server));
1897 ASSERT_EQ(OK, trust(&maliciousClient, server));
1898
1899 server->start();
1900
1901 // See UntrustedClient.
1902 bool readOk = rpcSecurity != RpcSecurity::TLS;
1903 maliciousClient.run(true, readOk);
1904}
1905
Yifan Hong67519322021-09-13 18:51:16 -07001906TEST_P(RpcTransportTest, Trigger) {
1907 std::string msg2 = ", world!";
1908 std::mutex writeMutex;
1909 std::condition_variable writeCv;
1910 bool shouldContinueWriting = false;
1911 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001912 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001913 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001914 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1915 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001916 if (status != OK) return AssertionFailure() << statusToString(status);
1917
1918 {
1919 std::unique_lock<std::mutex> lock(writeMutex);
1920 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1921 return AssertionFailure() << "write barrier not cleared in time!";
1922 }
1923 }
1924
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001925 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001926 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1927 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001928 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001929 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001930 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001931 << statusToString(status);
1932 return AssertionSuccess();
1933 };
1934
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001935 auto server = std::make_unique<Server>();
1936 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001937
1938 // Set up client
1939 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001940 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001941
1942 // Exchange keys
1943 ASSERT_EQ(OK, trust(&client, server));
1944 ASSERT_EQ(OK, trust(server, &client));
1945
1946 server->setPostConnect(serverPostConnect);
1947
Yifan Hong67519322021-09-13 18:51:16 -07001948 server->start();
1949 // connect() to server and do handshake
1950 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001951 // read the first message. This ensures that server has finished handshake and start handling
1952 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001953 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001954 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1955 // write is on an FdTrigger that has been shut down.
1956 server->shutdown();
1957 // Continues server thread to write the second message.
1958 {
Yifan Hong22211f82021-09-14 12:32:25 -07001959 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001960 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001961 }
Yifan Hong22211f82021-09-14 12:32:25 -07001962 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001963 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001964 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001965 // On the client side, second read fails with DEAD_OBJECT
1966 ASSERT_FALSE(client.readMessage(msg2));
1967}
1968
Pawan49d74cb2022-08-03 21:19:11 +00001969TEST_P(RpcTransportTest, CheckWaitingForRead) {
1970 std::mutex readMutex;
1971 std::condition_variable readCv;
1972 bool shouldContinueReading = false;
1973 // Server will write data on transport once its started
1974 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1975 std::string message(RpcTransportTestUtils::kMessage);
1976 iovec messageIov{message.data(), message.size()};
1977 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1978 std::nullopt, nullptr);
1979 if (status != OK) return AssertionFailure() << statusToString(status);
1980
1981 {
1982 std::unique_lock<std::mutex> lock(readMutex);
1983 shouldContinueReading = true;
1984 lock.unlock();
1985 readCv.notify_all();
1986 }
1987 return AssertionSuccess();
1988 };
1989
1990 // Setup Server and client
1991 auto server = std::make_unique<Server>();
1992 ASSERT_TRUE(server->setUp(GetParam()));
1993
1994 Client client(server->getConnectToServerFn());
1995 ASSERT_TRUE(client.setUp(GetParam()));
1996
1997 ASSERT_EQ(OK, trust(&client, server));
1998 ASSERT_EQ(OK, trust(server, &client));
1999 server->setPostConnect(serverPostConnect);
2000
2001 server->start();
2002 ASSERT_TRUE(client.setUpTransport());
2003 {
2004 // Wait till server writes data
2005 std::unique_lock<std::mutex> lock(readMutex);
2006 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2007 }
2008
2009 // Since there is no read polling here, we will get polling count 0
2010 ASSERT_FALSE(client.isTransportWaiting());
2011 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2012 // Thread should increment polling count, read and decrement polling count
2013 // Again, polling count should be zero here
2014 ASSERT_FALSE(client.isTransportWaiting());
2015
2016 server->shutdown();
2017}
2018
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002019INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2020 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2021 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002022
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002024 : public testing::TestWithParam<
2025 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026public:
2027 template <typename A, typename B>
2028 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002029 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2030 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002031 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2032 }
2033 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002034 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2035 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2036 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002037 };
2038};
2039
2040TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002041 if constexpr (!kEnableRpcThreads) {
2042 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2043 }
2044
Frederick Mayledc07cf82022-05-26 20:30:12 +00002045 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002046
2047 std::vector<uint8_t> pkeyData, certData;
2048 {
2049 auto pkey = makeKeyPairForSelfSignedCert();
2050 ASSERT_NE(nullptr, pkey);
2051 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2052 ASSERT_NE(nullptr, cert);
2053 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2054 certData = serializeCertificate(cert.get(), certificateFormat);
2055 }
2056
2057 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2058 auto desCert = deserializeCertificate(certData, certificateFormat);
2059 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002060 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2061 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002062
2063 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2064 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2065
2066 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2067 ASSERT_TRUE(client.setUp(utilsParam));
2068
2069 ASSERT_EQ(OK, trust(&client, server));
2070 ASSERT_EQ(OK, trust(server, &client));
2071
2072 server->start();
2073 client.run();
2074}
2075
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002076INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002077 BinderRpc, RpcTransportTlsKeyTest,
2078 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2079 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002080 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2081 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002082 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002083#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002084
Steven Morelandc1635952021-04-01 16:20:47 +00002085} // namespace android
2086
2087int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002088 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002089 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002090
Steven Moreland5553ac42020-11-11 02:14:45 +00002091 return RUN_ALL_TESTS();
2092}