blob: 624edba9cd3f0342a7facf35627d1582b0d49d1e [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
Andrei Homescu2a298012022-06-15 01:08:54 +000028#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070029#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000031#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000032
Andrei Homescud65666d2023-03-03 07:28:02 +000033#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000034#include <binder/RpcTransportTipcAndroid.h>
35#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000036#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000037
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -080038#include "../Utils.h"
Andrei Homescu2a298012022-06-15 01:08:54 +000039#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000040#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000041
Yifan Hong1a235852021-05-13 16:07:47 -070042using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070043using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070044using testing::AssertionFailure;
45using testing::AssertionResult;
46using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070047
Steven Moreland5553ac42020-11-11 02:14:45 +000048namespace android {
49
Andrei Homescu12106de2022-04-27 04:42:21 +000050#ifdef BINDER_TEST_NO_SHARED_LIBS
51constexpr bool kEnableSharedLibs = false;
52#else
53constexpr bool kEnableSharedLibs = true;
54#endif
55
Andrei Homescud65666d2023-03-03 07:28:02 +000056#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000057constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
58#endif
59
Frederick Maylea12b0962022-06-25 01:13:22 +000060static std::string WaitStatusToString(int wstatus) {
61 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000062 return std::format("exit status {}", WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000063 }
64 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000065 return std::format("term signal {}", WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000066 }
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000067 return std::format("unexpected state {}", wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000068}
69
Steven Moreland276d8df2022-09-28 23:56:39 +000070static void debugBacktrace(pid_t pid) {
71 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
72 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
73}
74
Steven Moreland5553ac42020-11-11 02:14:45 +000075class Process {
76public:
Andrei Homescu96834632022-10-14 00:49:49 +000077 Process(Process&& other)
78 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
79 mReadEnd(std::move(other.mReadEnd)),
80 mWriteEnd(std::move(other.mWriteEnd)) {
81 // The default move constructor doesn't clear mPid after moving it,
82 // which we need to do because the destructor checks for mPid!=0
83 mPid = other.mPid;
84 other.mPid = 0;
85 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070086 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
87 android::base::borrowed_fd /* readEnd */)>& f) {
88 android::base::unique_fd childWriteEnd;
89 android::base::unique_fd childReadEnd;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -070090 if (!android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
91 if (!android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +000092 if (0 == (mPid = fork())) {
93 // racey: assume parent doesn't crash before this is set
94 prctl(PR_SET_PDEATHSIG, SIGHUP);
95
Yifan Hong1deca4b2021-09-10 16:16:44 -070096 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000097
98 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000099 }
100 }
101 ~Process() {
102 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000103 int wstatus;
104 waitpid(mPid, &wstatus, 0);
105 if (mCustomExitStatusCheck) {
106 mCustomExitStatusCheck(wstatus);
107 } else {
108 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
109 << "server process failed: " << WaitStatusToString(wstatus);
110 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000111 }
112 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700113 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700114 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000115
Frederick Maylea12b0962022-06-25 01:13:22 +0000116 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
117 mCustomExitStatusCheck = std::move(f);
118 }
119
Frederick Mayle69a0c992022-05-26 20:38:39 +0000120 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
121 void terminate() { kill(mPid, SIGTERM); }
122
Steven Moreland276d8df2022-09-28 23:56:39 +0000123 pid_t getPid() { return mPid; }
124
Steven Moreland5553ac42020-11-11 02:14:45 +0000125private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000126 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700128 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700129 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000130};
131
132static std::string allocateSocketAddress() {
133 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000134 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000135 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700136 unlink(ret.c_str());
137 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000138};
139
Steven Morelandda573042021-06-12 01:13:45 +0000140static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000141 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000142 return vsockPort++;
143}
144
Alice Wang893a9912022-10-24 10:44:09 +0000145static base::unique_fd initUnixSocket(std::string addr) {
146 auto socket_addr = UnixSocketAddress(addr.c_str());
147 base::unique_fd fd(
148 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700149 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
150 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
151 PLOGF("initUnixSocket failed to bind");
152 }
Alice Wang893a9912022-10-24 10:44:09 +0000153 return fd;
154}
155
Andrei Homescu96834632022-10-14 00:49:49 +0000156// Destructors need to be defined, even if pure virtual
157ProcessSession::~ProcessSession() {}
158
159class LinuxProcessSession : public ProcessSession {
160public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000161 // reference to process hosting a socket server
162 Process host;
163
Andrei Homescu96834632022-10-14 00:49:49 +0000164 LinuxProcessSession(LinuxProcessSession&&) = default;
165 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
166 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000167 for (auto& session : sessions) {
168 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000169 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000170
Steven Moreland67f85902023-03-15 01:13:49 +0000171 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
172 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000174
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000175 EXPECT_NE(nullptr, session);
176 EXPECT_NE(nullptr, session->state());
177 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000178
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 wp<RpcSession> weakSession = session;
180 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000181
Steven Moreland57042712022-10-04 23:56:45 +0000182 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
183 // the object should not actually be promotable. By looping, we distinguish a race here
184 // from a bug causing the object to not be promotable.
185 for (size_t i = 0; i < 3; i++) {
186 sp<RpcSession> strongSession = weakSession.promote();
187 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000188 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000189 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
190 "Leaked sess: ")
191 << strongSession->getStrongCount() << " checked time " << i;
192
193 if (strongSession != nullptr) {
194 sleep(1);
195 }
196 }
Steven Moreland736664b2021-05-01 04:27:25 +0000197 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199
Andrei Homescu96834632022-10-14 00:49:49 +0000200 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
201 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000202 }
Andrei Homescu96834632022-10-14 00:49:49 +0000203
204 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000205};
206
Yifan Hong1deca4b2021-09-10 16:16:44 -0700207static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700208 base::unique_fd serverFd(
209 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700210 if (!serverFd.ok()) {
211 PLOGF("Could not create socket %s", addr.toString().c_str());
212 }
Steven Moreland4198a122021-08-03 17:37:58 -0700213
214 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700215 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700216 }
217 return serverFd;
218}
219
Andrei Homescud65666d2023-03-03 07:28:02 +0000220#ifndef BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100221static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
222 base::unique_fd sockClient, sockServer;
223 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700224 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100225 }
226
227 int zero = 0;
228 iovec iov{&zero, sizeof(zero)};
229 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
230 fds.emplace_back(std::move(sockServer));
231
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000232 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700233 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100234 }
235 return std::move(sockClient);
236}
Andrei Homescud65666d2023-03-03 07:28:02 +0000237#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100238
Andrei Homescuf30148c2023-03-10 00:31:45 +0000239std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
240 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000241}
Andrei Homescu2a298012022-06-15 01:08:54 +0000242
Andrei Homescu96834632022-10-14 00:49:49 +0000243// This creates a new process serving an interface on a certain number of
244// threads.
245std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
246 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700247 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000248
Steven Moreland67f85902023-03-15 01:13:49 +0000249 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700250 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
251 "%s: %zu != %zu", __func__,
252 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000253 }
254
Steven Morelandb469f432023-07-28 22:13:47 +0000255 SocketType socketType = GetParam().type;
256 RpcSecurity rpcSecurity = GetParam().security;
257 uint32_t clientVersion = GetParam().clientVersion;
258 uint32_t serverVersion = GetParam().serverVersion;
259 bool singleThreaded = GetParam().singleThreaded;
260 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000261
262 std::string path = android::base::GetExecutableDirectory();
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000263 auto servicePath =
264 std::format("{}/binder_rpc_test_service{}{}", path,
265 singleThreaded ? "_single_threaded" : "", noKernel ? "_no_kernel" : "");
Andrei Homescu96834632022-10-14 00:49:49 +0000266
Alice Wang1ef010b2022-11-14 09:09:25 +0000267 base::unique_fd bootstrapClientFd, socketFd;
268
Alice Wang893a9912022-10-24 10:44:09 +0000269 auto addr = allocateSocketAddress();
270 // Initializes the socket before the fork/exec.
271 if (socketType == SocketType::UNIX_RAW) {
272 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000273 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
274 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
275 // This is because we cannot pass ParcelFileDescriptor over a pipe.
276 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700277 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000278 }
Alice Wang893a9912022-10-24 10:44:09 +0000279 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000280
Andrei Homescu96834632022-10-14 00:49:49 +0000281 auto ret = std::make_unique<LinuxProcessSession>(
282 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000283 if (socketType == SocketType::TIPC) {
284 // Trusty has a single persistent service
285 return;
286 }
287
Andrei Homescu96834632022-10-14 00:49:49 +0000288 auto writeFd = std::to_string(writeEnd.get());
289 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800290 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
291 readFd.c_str(), NULL);
292 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
293 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000294 }));
295
296 BinderRpcTestServerConfig serverConfig;
297 serverConfig.numThreads = options.numThreads;
298 serverConfig.socketType = static_cast<int32_t>(socketType);
299 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
300 serverConfig.serverVersion = serverVersion;
301 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000302 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000303 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000304 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
305 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
306 static_cast<int32_t>(mode));
307 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000308 if (socketType != SocketType::TIPC) {
309 writeToFd(ret->host.writeEnd(), serverConfig);
310 }
Andrei Homescu96834632022-10-14 00:49:49 +0000311
312 std::vector<sp<RpcSession>> sessions;
313 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
314 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000315 std::unique_ptr<RpcTransportCtxFactory> factory;
316 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000317#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000318 factory = RpcTransportCtxFactoryTipcAndroid::make();
319#else
320 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
321#endif
322 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000323 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000324 }
325 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100326 }
327
Andrei Homescu68a55612022-08-02 01:25:15 +0000328 BinderRpcTestServerInfo serverInfo;
329 if (socketType != SocketType::TIPC) {
330 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
331 BinderRpcTestClientInfo clientInfo;
332 for (const auto& session : sessions) {
333 auto& parcelableCert = clientInfo.certs.emplace_back();
334 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
335 }
336 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000337
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700338 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000339 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700340 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000341 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000342
Andrei Homescu68a55612022-08-02 01:25:15 +0000343 if (rpcSecurity == RpcSecurity::TLS) {
344 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700345 LOG_ALWAYS_FATAL_IF(
346 OK !=
347 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000348 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700349 }
350
Andrei Homescu96834632022-10-14 00:49:49 +0000351 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000352
Steven Moreland67f85902023-03-15 01:13:49 +0000353 for (size_t i = 0; i < sessions.size(); i++) {
354 const auto& session = sessions.at(i);
355
356 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
357 ? options.numIncomingConnectionsBySession.at(i)
358 : 0;
359
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700360 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000361 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000362 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000363 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000364
Andrei Homescu96834632022-10-14 00:49:49 +0000365 switch (socketType) {
366 case SocketType::PRECONNECTED:
367 status = session->setupPreconnectedClient({}, [=]() {
368 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
369 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000370 break;
Alice Wang893a9912022-10-24 10:44:09 +0000371 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000372 case SocketType::UNIX:
373 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
374 break;
375 case SocketType::UNIX_BOOTSTRAP:
376 status = session->setupUnixDomainSocketBootstrapClient(
377 base::unique_fd(dup(bootstrapClientFd.get())));
378 break;
379 case SocketType::VSOCK:
380 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
381 break;
382 case SocketType::INET:
383 status = session->setupInetClient("127.0.0.1", serverInfo.port);
384 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000385 case SocketType::TIPC:
386 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000387#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000388 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000389 for (size_t i = 0; i < 5; i++) {
390 // Try to connect several times,
391 // in case the service is slow to start
392 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
393 if (tipcFd >= 0) {
394 return android::base::unique_fd(tipcFd);
395 }
396 usleep(50000);
397 }
398 return android::base::unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000399#else
400 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
401 return android::base::unique_fd();
402#endif
403 });
404 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000405 default:
406 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000407 }
Andrei Homescu96834632022-10-14 00:49:49 +0000408 if (options.allowConnectFailure && status != OK) {
409 ret->sessions.clear();
410 break;
411 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700412 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Andrei Homescu96834632022-10-14 00:49:49 +0000413 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000414 }
Andrei Homescu96834632022-10-14 00:49:49 +0000415 return ret;
416}
Steven Morelandc1635952021-04-01 16:20:47 +0000417
Andrei Homescua858b0e2022-08-01 23:43:09 +0000418TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
419 if (clientOrServerSingleThreaded()) {
420 GTEST_SKIP() << "This test requires multiple threads";
421 }
422
Steven Moreland5553ac42020-11-11 02:14:45 +0000423 constexpr size_t kNumThreads = 10;
424
Steven Moreland4313d7e2021-07-15 23:41:22 +0000425 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000426
427 EXPECT_OK(proc.rootIface->lock());
428
429 // block all but one thread taking locks
430 std::vector<std::thread> ts;
431 for (size_t i = 0; i < kNumThreads - 1; i++) {
432 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
433 }
434
Steven Morelandd6d816f2022-12-23 01:37:17 +0000435 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000436
437 // other calls still work
438 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
439
Steven Morelandd6d816f2022-12-23 01:37:17 +0000440 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 size_t epochMsBefore = epochMillis();
442 // after this, we should never see a response within this time
443 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
444
445 // this call should be blocked for blockTimeMs
446 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
447
448 size_t epochMsAfter = epochMillis();
449 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
450
451 for (auto& t : ts) t.join();
452}
453
Steven Moreland27f620a2023-03-06 19:44:36 +0000454static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 size_t epochMsBefore = epochMillis();
456
457 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700458 for (size_t i = 0; i < numCalls; i++) {
459 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000460 }
461
462 for (auto& t : ts) t.join();
463
464 size_t epochMsAfter = epochMillis();
465
Yifan Hong1f44f982021-10-08 17:16:47 -0700466 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000467
Steven Moreland9c203222023-05-31 21:26:41 +0000468 // Potential flake, but make sure calls are handled in parallel. Due
469 // to past flakes, this only checks that the amount of time taken has
470 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
471 // check this more exactly.
472 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700473}
474
Andrei Homescua858b0e2022-08-01 23:43:09 +0000475TEST_P(BinderRpc, ThreadPoolOverSaturated) {
476 if (clientOrServerSingleThreaded()) {
477 GTEST_SKIP() << "This test requires multiple threads";
478 }
479
Yifan Hong1f44f982021-10-08 17:16:47 -0700480 constexpr size_t kNumThreads = 10;
481 constexpr size_t kNumCalls = kNumThreads + 3;
482 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000483
484 // b/272429574 - below 500ms, the test fails
485 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700486}
487
Andrei Homescua858b0e2022-08-01 23:43:09 +0000488TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
489 if (clientOrServerSingleThreaded()) {
490 GTEST_SKIP() << "This test requires multiple threads";
491 }
492
Yifan Hong1f44f982021-10-08 17:16:47 -0700493 constexpr size_t kNumThreads = 20;
494 constexpr size_t kNumOutgoingConnections = 10;
495 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
496 auto proc = createRpcTestSocketServerProcess(
497 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000498
499 // b/272429574 - below 500ms, the test fails
500 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000501}
502
Andrei Homescua858b0e2022-08-01 23:43:09 +0000503TEST_P(BinderRpc, ThreadingStressTest) {
504 if (clientOrServerSingleThreaded()) {
505 GTEST_SKIP() << "This test requires multiple threads";
506 }
507
Steven Moreland27f620a2023-03-06 19:44:36 +0000508 constexpr size_t kNumClientThreads = 5;
509 constexpr size_t kNumServerThreads = 5;
510 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000511
Steven Moreland4313d7e2021-07-15 23:41:22 +0000512 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000513
514 std::vector<std::thread> threads;
515 for (size_t i = 0; i < kNumClientThreads; i++) {
516 threads.push_back(std::thread([&] {
517 for (size_t j = 0; j < kNumCalls; j++) {
518 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000519 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000520 EXPECT_EQ(proc.rootBinder, out);
521 }
522 }));
523 }
524
525 for (auto& t : threads) t.join();
526}
527
Steven Moreland925ba0a2021-09-17 18:06:32 -0700528static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
529 std::vector<std::thread> threads;
530 for (size_t i = 0; i < threadCount; i++) {
531 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
532 }
533 for (auto& t : threads) t.join();
534}
535
Andrei Homescua858b0e2022-08-01 23:43:09 +0000536TEST_P(BinderRpc, OnewayStressTest) {
537 if (clientOrServerSingleThreaded()) {
538 GTEST_SKIP() << "This test requires multiple threads";
539 }
540
Steven Morelandc6046982021-04-20 00:49:42 +0000541 constexpr size_t kNumClientThreads = 10;
542 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700543 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000544
Steven Moreland4313d7e2021-07-15 23:41:22 +0000545 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000546
547 std::vector<std::thread> threads;
548 for (size_t i = 0; i < kNumClientThreads; i++) {
549 threads.push_back(std::thread([&] {
550 for (size_t j = 0; j < kNumCalls; j++) {
551 EXPECT_OK(proc.rootIface->sendString("a"));
552 }
Steven Morelandc6046982021-04-20 00:49:42 +0000553 }));
554 }
555
556 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700557
558 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000559}
560
Frederick Mayleb0221d12022-10-03 23:10:53 +0000561TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
562 if (!supportsFdTransport()) {
563 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
564 }
565 if (clientOrServerSingleThreaded()) {
566 GTEST_SKIP() << "This test requires multiple threads";
567 }
568
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000569 constexpr size_t kNumServerThreads = 3;
570
Frederick Mayleb0221d12022-10-03 23:10:53 +0000571 // This test forces a oneway transaction to be queued by issuing two
572 // `blockingSendFdOneway` calls, then drains the queue by issuing two
573 // `blockingRecvFd` calls.
574 //
575 // For more details about the queuing semantics see
576 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
577
578 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000579 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000580 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
581 .serverSupportedFileDescriptorTransportModes =
582 {RpcSession::FileDescriptorTransportMode::UNIX},
583 });
584
585 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
586 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
587 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
588 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
589
590 android::os::ParcelFileDescriptor fdA;
591 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
592 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700593 ASSERT_TRUE(android::base::ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000594 EXPECT_EQ(result, "a");
595
596 android::os::ParcelFileDescriptor fdB;
597 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700598 ASSERT_TRUE(android::base::ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000599 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000600
601 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000602}
603
Andrei Homescua858b0e2022-08-01 23:43:09 +0000604TEST_P(BinderRpc, OnewayCallQueueing) {
605 if (clientOrServerSingleThreaded()) {
606 GTEST_SKIP() << "This test requires multiple threads";
607 }
608
Frederick Mayle96872592023-03-07 14:56:15 -0800609 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000610 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000611
612 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000613 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000614
Frederick Mayle96872592023-03-07 14:56:15 -0800615 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700616 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800617 for (size_t i = 0; i + 1 < kNumQueued; i++) {
618 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000619 }
Frederick Mayle96872592023-03-07 14:56:15 -0800620 for (size_t i = 0; i + 1 < kNumQueued; i++) {
621 int n;
622 proc.rootIface->blockingRecvInt(&n);
623 EXPECT_EQ(n, i);
624 }
Steven Morelandf5174272021-05-25 00:39:28 +0000625
Steven Moreland925ba0a2021-09-17 18:06:32 -0700626 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000627}
628
Andrei Homescua858b0e2022-08-01 23:43:09 +0000629TEST_P(BinderRpc, OnewayCallExhaustion) {
630 if (clientOrServerSingleThreaded()) {
631 GTEST_SKIP() << "This test requires multiple threads";
632 }
633
Steven Morelandd45be622021-06-04 02:19:37 +0000634 constexpr size_t kNumClients = 2;
635 constexpr size_t kTooLongMs = 1000;
636
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000638
639 // Build up oneway calls on the second session to make sure it terminates
640 // and shuts down. The first session should be unaffected (proc destructor
641 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000642 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000643
644 std::vector<std::thread> threads;
645 for (size_t i = 0; i < kNumClients; i++) {
646 // one of these threads will get stuck queueing a transaction once the
647 // socket fills up, the other will be able to fill up transactions on
648 // this object
649 threads.push_back(std::thread([&] {
650 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
651 }
652 }));
653 }
654 for (auto& t : threads) t.join();
655
656 Status status = iface->sleepMsAsync(kTooLongMs);
657 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
658
Steven Moreland798e0d12021-07-14 23:19:25 +0000659 // now that it has died, wait for the remote session to shutdown
660 std::vector<int32_t> remoteCounts;
661 do {
662 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
663 } while (remoteCounts.size() == kNumClients);
664
Steven Morelandd45be622021-06-04 02:19:37 +0000665 // the second session should be shutdown in the other process by the time we
666 // are able to join above (it'll only be hung up once it finishes processing
667 // any pending commands). We need to erase this session from the record
668 // here, so that the destructor for our session won't check that this
669 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000670 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000671}
672
Steven Moreland67f85902023-03-15 01:13:49 +0000673TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
674 if (clientOrServerSingleThreaded()) {
675 GTEST_SKIP() << "This test requires multiple threads";
676 }
677
678 // session 0 - will check for leaks in destrutor of proc
679 // session 1 - we want to make sure it gets deleted when we drop all references to it
680 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700681 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000682
683 wp<RpcSession> session = proc.proc->sessions.at(1).session;
684
685 // remove all references to the second session
686 proc.proc->sessions.at(1).root = nullptr;
687 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
688
689 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
690 // to drain commands.
691 for (size_t i = 0; i < 100; i++) {
692 usleep(10 * 1000);
693 if (session.promote() == nullptr) break;
694 }
695
696 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000697
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000698 // now that it has died, wait for the remote session to shutdown
699 std::vector<int32_t> remoteCounts;
700 do {
701 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
702 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000703}
704
Devin Moore66d5b7a2022-07-07 21:42:10 +0000705TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000706 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000707 GTEST_SKIP() << "This test requires multiple threads";
708 }
709 class MyDeathRec : public IBinder::DeathRecipient {
710 public:
711 void binderDied(const wp<IBinder>& /* who */) override {
712 dead = true;
713 mCv.notify_one();
714 }
715 std::mutex mMtx;
716 std::condition_variable mCv;
717 bool dead = false;
718 };
719
720 // Death recipient needs to have an incoming connection to be called
721 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000722 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000723
724 auto dr = sp<MyDeathRec>::make();
725 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
726
727 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
728 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
729 }
730
731 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000732 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000733
734 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000735 // can't do this before checking the death recipient by calling
736 // forceShutdown earlier, because shutdownAndWait will also trigger
737 // a death recipient, but if we had a way to wait for the service
738 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000739 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000740 proc.expectAlreadyShutdown = true;
741}
742
743TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000744 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000745 GTEST_SKIP() << "This test requires multiple threads";
746 }
747 class MyDeathRec : public IBinder::DeathRecipient {
748 public:
749 void binderDied(const wp<IBinder>& /* who */) override {
750 dead = true;
751 mCv.notify_one();
752 }
753 std::mutex mMtx;
754 std::condition_variable mCv;
755 bool dead = false;
756 };
757
758 // Death recipient needs to have an incoming connection to be called
759 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000760 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000761
762 auto dr = sp<MyDeathRec>::make();
763 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
764
765 // Explicitly calling shutDownAndWait will cause the death recipients
766 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000767 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000768
769 std::unique_lock<std::mutex> lock(dr->mMtx);
770 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000771 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000772 }
773 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
774
Andrei Homescu96834632022-10-14 00:49:49 +0000775 proc.proc->terminate();
776 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000777 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
778 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
779 });
780 proc.expectAlreadyShutdown = true;
781}
782
Steven Moreland5ec743f2023-01-18 01:02:06 +0000783TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000784 if (socketType() == SocketType::TIPC) {
785 // This should work, but Trusty takes too long to restart the service
786 GTEST_SKIP() << "Service death test not supported on Trusty";
787 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000788 class MyDeathRec : public IBinder::DeathRecipient {
789 public:
790 void binderDied(const wp<IBinder>& /* who */) override {}
791 };
792
Steven Moreland67f85902023-03-15 01:13:49 +0000793 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000794
795 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000796 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000797}
798
799TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000800 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000801 GTEST_SKIP() << "This test requires multiple threads";
802 }
803 class MyDeathRec : public IBinder::DeathRecipient {
804 public:
805 void binderDied(const wp<IBinder>& /* who */) override {
806 GTEST_FAIL() << "This should not be called after unlinkToDeath";
807 }
808 };
809
810 // Death recipient needs to have an incoming connection to be called
811 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000812 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000813
814 auto dr = sp<MyDeathRec>::make();
815 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
816 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
817
Steven Moreland67f85902023-03-15 01:13:49 +0000818 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000819}
820
Steven Morelandc1635952021-04-01 16:20:47 +0000821TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000822 if (socketType() == SocketType::TIPC) {
823 // This should work, but Trusty takes too long to restart the service
824 GTEST_SKIP() << "Service death test not supported on Trusty";
825 }
826
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000828 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000829
830 // make sure there is some state during crash
831 // 1. we hold their binder
832 sp<IBinderRpcSession> session;
833 EXPECT_OK(proc.rootIface->openSession("happy", &session));
834 // 2. they hold our binder
835 sp<IBinder> binder = new BBinder();
836 EXPECT_OK(proc.rootIface->holdBinder(binder));
837
838 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
839 << "Do death cleanup: " << doDeathCleanup;
840
Andrei Homescu96834632022-10-14 00:49:49 +0000841 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000842 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
843 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
844 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000845 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 }
847}
848
Steven Morelandd7302072021-05-15 01:32:04 +0000849TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000850 // This test only works if the current process shared the internal state of
851 // ProcessState with the service across the call to fork(). Both the static
852 // libraries and libbinder.so have their own separate copies of all the
853 // globals, so the test only works when the test client and service both use
854 // libbinder.so (when using static libraries, even a client and service
855 // using the same kind of static library should have separate copies of the
856 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000857 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000858 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
859 "at build time.";
860 }
861
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000863
Andrei Homescu2a298012022-06-15 01:08:54 +0000864 // we can't allocate IPCThreadState so actually the first time should
865 // succeed :(
866 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000867
868 // second time! we catch the error :)
869 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
870
Andrei Homescu96834632022-10-14 00:49:49 +0000871 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000872 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
873 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
874 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000875 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000876}
877
Frederick Mayle69a0c992022-05-26 20:38:39 +0000878TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000879 if (socketType() == SocketType::TIPC) {
880 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
881 }
882
Frederick Mayle69a0c992022-05-26 20:38:39 +0000883 auto proc = createRpcTestSocketServerProcess({
884 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
885 .serverSupportedFileDescriptorTransportModes =
886 {RpcSession::FileDescriptorTransportMode::UNIX},
887 .allowConnectFailure = true,
888 });
Andrei Homescu96834632022-10-14 00:49:49 +0000889 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
890 proc.proc->terminate();
891 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000892 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
893 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
894 });
895 proc.expectAlreadyShutdown = true;
896}
897
898TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000899 if (socketType() == SocketType::TIPC) {
900 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
901 }
902
Frederick Mayle69a0c992022-05-26 20:38:39 +0000903 auto proc = createRpcTestSocketServerProcess({
904 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
905 .serverSupportedFileDescriptorTransportModes =
906 {RpcSession::FileDescriptorTransportMode::NONE},
907 .allowConnectFailure = true,
908 });
Andrei Homescu96834632022-10-14 00:49:49 +0000909 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
910 proc.proc->terminate();
911 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000912 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
913 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
914 });
915 proc.expectAlreadyShutdown = true;
916}
917
918TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000919 if (socketType() == SocketType::TIPC) {
920 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
921 }
922
Frederick Mayle69a0c992022-05-26 20:38:39 +0000923 auto proc = createRpcTestSocketServerProcess({
924 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
925 .serverSupportedFileDescriptorTransportModes =
926 {RpcSession::FileDescriptorTransportMode::NONE,
927 RpcSession::FileDescriptorTransportMode::UNIX},
928 });
929
930 android::os::ParcelFileDescriptor out;
931 auto status = proc.rootIface->echoAsFile("hello", &out);
932 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
933}
934
935TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000936 if (socketType() == SocketType::TIPC) {
937 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
938 }
939
Frederick Mayle69a0c992022-05-26 20:38:39 +0000940 auto proc = createRpcTestSocketServerProcess({
941 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
942 .serverSupportedFileDescriptorTransportModes =
943 {RpcSession::FileDescriptorTransportMode::UNIX},
944 });
945
946 android::os::ParcelFileDescriptor out;
947 auto status = proc.rootIface->echoAsFile("hello", &out);
948 if (!supportsFdTransport()) {
949 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
950 return;
951 }
952 ASSERT_TRUE(status.isOk()) << status;
953
954 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700955 ASSERT_TRUE(android::base::ReadFdToString(out.get(), &result));
956 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000957}
958
959TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000960 if (socketType() == SocketType::TIPC) {
961 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
962 }
963
Frederick Mayle69a0c992022-05-26 20:38:39 +0000964 auto proc = createRpcTestSocketServerProcess({
965 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
966 .serverSupportedFileDescriptorTransportModes =
967 {RpcSession::FileDescriptorTransportMode::UNIX},
968 });
969
970 std::vector<android::os::ParcelFileDescriptor> files;
971 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
972 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
973 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
975
976 android::os::ParcelFileDescriptor out;
977 auto status = proc.rootIface->concatFiles(files, &out);
978 if (!supportsFdTransport()) {
979 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
980 return;
981 }
982 ASSERT_TRUE(status.isOk()) << status;
983
984 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700985 EXPECT_TRUE(android::base::ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000986 EXPECT_EQ(result, "123abcd");
987}
988
989TEST_P(BinderRpc, SendMaxFiles) {
990 if (!supportsFdTransport()) {
991 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
992 }
993
994 auto proc = createRpcTestSocketServerProcess({
995 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
996 .serverSupportedFileDescriptorTransportModes =
997 {RpcSession::FileDescriptorTransportMode::UNIX},
998 });
999
1000 std::vector<android::os::ParcelFileDescriptor> files;
1001 for (int i = 0; i < 253; i++) {
1002 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1003 }
1004
1005 android::os::ParcelFileDescriptor out;
1006 auto status = proc.rootIface->concatFiles(files, &out);
1007 ASSERT_TRUE(status.isOk()) << status;
1008
1009 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001010 EXPECT_TRUE(android::base::ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001011 EXPECT_EQ(result, std::string(253, 'a'));
1012}
1013
1014TEST_P(BinderRpc, SendTooManyFiles) {
1015 if (!supportsFdTransport()) {
1016 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1017 }
1018
1019 auto proc = createRpcTestSocketServerProcess({
1020 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1021 .serverSupportedFileDescriptorTransportModes =
1022 {RpcSession::FileDescriptorTransportMode::UNIX},
1023 });
1024
1025 std::vector<android::os::ParcelFileDescriptor> files;
1026 for (int i = 0; i < 254; i++) {
1027 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1028 }
1029
1030 android::os::ParcelFileDescriptor out;
1031 auto status = proc.rootIface->concatFiles(files, &out);
1032 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1033}
1034
Andrei Homescufc221502022-10-08 03:51:17 +00001035TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001036 if (socketType() == SocketType::TIPC) {
1037 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1038 }
1039
Andrei Homescufc221502022-10-08 03:51:17 +00001040 auto proc = createRpcTestSocketServerProcess({
1041 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1042 .serverSupportedFileDescriptorTransportModes =
1043 {RpcSession::FileDescriptorTransportMode::UNIX},
1044 });
1045
1046 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1047 ASSERT_NE(badFd, -1);
1048
1049 // Close the file descriptor so it becomes invalid for dup
1050 close(badFd);
1051
1052 Parcel p1;
1053 p1.markForBinder(proc.rootBinder);
1054 p1.writeInt32(3);
1055 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1056
1057 Parcel pRaw;
1058 pRaw.markForBinder(proc.rootBinder);
1059 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1060
1061 pRaw.setDataPosition(0);
1062 EXPECT_EQ(3, pRaw.readInt32());
1063 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1064}
1065
Andrei Homescu68a55612022-08-02 01:25:15 +00001066#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001067TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001068 if constexpr (!kEnableSharedLibs) {
1069 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1070 }
1071
Steven Moreland4313d7e2021-07-15 23:41:22 +00001072 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001073
1074 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1075 ASSERT_NE(binder, nullptr);
1076
1077 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1078}
1079
1080TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001081 if constexpr (!kEnableSharedLibs) {
1082 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1083 }
1084
Steven Moreland4313d7e2021-07-15 23:41:22 +00001085 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001086
1087 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1088 ASSERT_NE(binder, nullptr);
1089
1090 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1091 ASSERT_NE(ndkBinder, nullptr);
1092
1093 std::string out;
1094 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1095 ASSERT_TRUE(status.isOk()) << status.getDescription();
1096 ASSERT_EQ("aoeuaoeu", out);
1097}
Andrei Homescu68a55612022-08-02 01:25:15 +00001098#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001099
Steven Moreland5553ac42020-11-11 02:14:45 +00001100ssize_t countFds() {
1101 DIR* dir = opendir("/proc/self/fd/");
1102 if (dir == nullptr) return -1;
1103 ssize_t ret = 0;
1104 dirent* ent;
1105 while ((ent = readdir(dir)) != nullptr) ret++;
1106 closedir(dir);
1107 return ret;
1108}
1109
Andrei Homescua858b0e2022-08-01 23:43:09 +00001110TEST_P(BinderRpc, Fds) {
1111 if (serverSingleThreaded()) {
1112 GTEST_SKIP() << "This test requires multiple threads";
1113 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001114 if (socketType() == SocketType::TIPC) {
1115 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1116 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001117
Steven Moreland5553ac42020-11-11 02:14:45 +00001118 ssize_t beforeFds = countFds();
1119 ASSERT_GE(beforeFds, 0);
1120 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001121 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001122 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1123 }
1124 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1125}
1126
Andrei Homescud65666d2023-03-03 07:28:02 +00001127#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001128
1129static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1130 std::vector<BinderRpc::ParamType> ret;
1131
1132 for (const auto& clientVersion : testVersions()) {
1133 for (const auto& serverVersion : testVersions()) {
1134 ret.push_back(BinderRpc::ParamType{
1135 .type = SocketType::TIPC,
1136 .security = RpcSecurity::RAW,
1137 .clientVersion = clientVersion,
1138 .serverVersion = serverVersion,
1139 .singleThreaded = true,
1140 .noKernel = true,
1141 });
1142 }
1143 }
1144
1145 return ret;
1146}
1147
1148INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
Andrei Homescud65666d2023-03-03 07:28:02 +00001149 BinderRpc::PrintParamInfo);
1150#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001151bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001152 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001153 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001154
Andrei Homescu992a4052022-06-28 21:26:18 +00001155 android::base::unique_fd serverFd(
1156 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001157
1158 if (errno == EAFNOSUPPORT) {
1159 return false;
1160 }
1161
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001162 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001163
1164 sockaddr_vm serverAddr{
1165 .svm_family = AF_VSOCK,
1166 .svm_port = vsockPort,
1167 .svm_cid = VMADDR_CID_ANY,
1168 };
1169 int ret = TEMP_FAILURE_RETRY(
1170 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1171 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1172 strerror(errno));
1173
1174 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1175 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1176 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.
1182 android::base::unique_fd connectFd(
1183 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001184 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
Andrei Homescu992a4052022-06-28 21:26:18 +00001185 strerror(errno));
1186
1187 bool success = false;
1188 sockaddr_vm connectAddr{
1189 .svm_family = AF_VSOCK,
1190 .svm_port = vsockPort,
1191 .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)) {
1196 android::base::unique_fd acceptFd;
1197 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}) {
1279 for (bool noKernel : {false, true}) {
1280 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,
1300 .noKernel = false,
1301 });
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
1308INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
Yifan Hong702115c2021-06-24 15:39:18 -07001309 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
1337INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001338 ::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();
1384 ASSERT_GE(descriptor.size(), 0);
1385 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) {
1426 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1427 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());
1433 base::unique_fd retrieved = server->releaseServer();
1434 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
Frederick Mayledc07cf82022-05-26 20:30:12 +00001468INSTANTIATE_TEST_CASE_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>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001479 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001480
1481 // A server that handles client socket connections.
1482 class Server {
1483 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001484 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1485
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: {
1513 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1514 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1515 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: {
1539 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001540 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001541 if (status != OK) {
1542 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1543 }
1544 mConnectToServer = [port] {
1545 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1546 };
1547 } break;
1548 case SocketType::INET: {
1549 unsigned int port;
1550 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1551 if (status != OK) {
1552 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1553 }
1554 mConnectToServer = [port] {
1555 const char* addr = kLocalInetAddress;
1556 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1557 if (aiStart == nullptr) return base::unique_fd{};
1558 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1559 auto fd = connectTo(
1560 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1561 if (fd.ok()) return fd;
1562 }
1563 ALOGE("None of the socket address resolved for %s:%u can be connected",
1564 addr, port);
1565 return base::unique_fd{};
1566 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001567 } break;
1568 case SocketType::TIPC: {
1569 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1570 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001571 }
1572 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001573 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001574 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001575 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1576 mSetup = true;
1577 return AssertionSuccess();
1578 }
1579 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1580 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1581 return mCertVerifier;
1582 }
1583 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1584 void start() {
1585 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1586 mThread = std::make_unique<std::thread>(&Server::run, this);
1587 }
David Brazdil21c887c2022-09-23 12:25:18 +01001588
1589 base::unique_fd acceptServerConnection() {
1590 return base::unique_fd(TEMP_FAILURE_RETRY(
1591 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1592 }
1593
1594 base::unique_fd recvmsgServerConnection() {
1595 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1596 int buf;
1597 iovec iov{&buf, sizeof(buf)};
1598
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001599 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001600 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001601 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001602 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1603 fds.size());
David Brazdil21c887c2022-09-23 12:25:18 +01001604 return std::move(std::get<base::unique_fd>(fds[0]));
1605 }
1606
Yifan Hong1deca4b2021-09-10 16:16:44 -07001607 void run() {
1608 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1609
1610 std::vector<std::thread> threads;
1611 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001612 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001613 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1614 }
1615
1616 for (auto& thread : threads) thread.join();
1617 }
1618 void handleOne(android::base::unique_fd acceptedFd) {
1619 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001620 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001621 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001622 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001623 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001624 }
Yifan Honge07d2732021-09-13 21:59:14 -07001625 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001626 shutdown();
1627 join();
1628 }
1629 void shutdown() { mFdTrigger->trigger(); }
1630
1631 void setPostConnect(
1632 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1633 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001634 }
1635
1636 private:
1637 std::unique_ptr<std::thread> mThread;
1638 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001639 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001641 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 std::unique_ptr<RpcTransportCtx> mCtx;
1643 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1644 std::make_shared<RpcCertificateVerifierSimple>();
1645 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001646 // The function invoked after connection and handshake. By default, it is
1647 // |defaultPostConnect| that sends |kMessage| to the client.
1648 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1649 Server::defaultPostConnect;
1650
1651 void join() {
1652 if (mThread != nullptr) {
1653 mThread->join();
1654 mThread = nullptr;
1655 }
1656 }
1657
1658 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1659 FdTrigger* fdTrigger) {
1660 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001661 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001662 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001663 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001664 if (status != OK) return AssertionFailure() << statusToString(status);
1665 return AssertionSuccess();
1666 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001667 };
1668
1669 class Client {
1670 public:
1671 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1672 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001673 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001674 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1675 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001676 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001677 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001678 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1679 return AssertionSuccess();
1680 }
1681 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1682 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1683 return mCertVerifier;
1684 }
Yifan Hong67519322021-09-13 18:51:16 -07001685 // connect() and do handshake
1686 bool setUpTransport() {
1687 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001688 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001689 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1690 return mClientTransport != nullptr;
1691 }
1692 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1693 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1694 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001695 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001696 status_t readStatus =
1697 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001698 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001699 if (readStatus != OK) {
1700 return AssertionFailure() << statusToString(readStatus);
1701 }
1702 if (readMessage != expectedMessage) {
1703 return AssertionFailure()
1704 << "Expected " << expectedMessage << ", actual " << readMessage;
1705 }
1706 return AssertionSuccess();
1707 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001708 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001709 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001710 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1711 return;
1712 }
1713 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001714 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001715 }
1716
Pawan49d74cb2022-08-03 21:19:11 +00001717 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1718
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719 private:
1720 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001721 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001722 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1723 std::unique_ptr<RpcTransportCtx> mCtx;
1724 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1725 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001726 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 };
1728
1729 // Make A trust B.
1730 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001731 static status_t trust(RpcSecurity rpcSecurity,
1732 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1733 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001734 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001735 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1736 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1737 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738 }
1739
1740 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001741};
1742
1743class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1744public:
1745 using Server = RpcTransportTestUtils::Server;
1746 using Client = RpcTransportTestUtils::Client;
1747 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001748 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001749 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001750 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001751 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001752 return ret;
1753 }
1754 static std::vector<ParamType> getRpcTranportTestParams() {
1755 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001756 for (auto serverVersion : testVersions()) {
1757 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1758 for (auto rpcSecurity : RpcSecurityValues()) {
1759 switch (rpcSecurity) {
1760 case RpcSecurity::RAW: {
1761 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1762 } break;
1763 case RpcSecurity::TLS: {
1764 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1765 serverVersion);
1766 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1767 serverVersion);
1768 } break;
1769 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001770 }
1771 }
1772 }
1773 return ret;
1774 }
1775 template <typename A, typename B>
1776 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001777 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1778 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001779 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1780 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001781 void SetUp() override {
1782 if constexpr (!kEnableRpcThreads) {
1783 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1784 }
1785 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001786};
1787
1788TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001789 auto server = std::make_unique<Server>();
1790 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791
1792 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001793 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794
1795 ASSERT_EQ(OK, trust(&client, server));
1796 ASSERT_EQ(OK, trust(server, &client));
1797
1798 server->start();
1799 client.run();
1800}
1801
1802TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001803 auto server = std::make_unique<Server>();
1804 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001805
1806 std::vector<Client> clients;
1807 for (int i = 0; i < 2; i++) {
1808 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001809 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001810 ASSERT_EQ(OK, trust(&client, server));
1811 ASSERT_EQ(OK, trust(server, &client));
1812 }
1813
1814 server->start();
1815 for (auto& client : clients) client.run();
1816}
1817
1818TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001819 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1820 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001821
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001822 auto untrustedServer = std::make_unique<Server>();
1823 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824
1825 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001826 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001827
1828 ASSERT_EQ(OK, trust(untrustedServer, &client));
1829
1830 untrustedServer->start();
1831
1832 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1833 // the client can't verify the server's identity.
1834 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1835 client.run(handshakeOk);
1836}
1837TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001838 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1839 (void)serverVersion;
1840
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001841 auto validServer = std::make_unique<Server>();
1842 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001843
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001844 auto maliciousServer = std::make_unique<Server>();
1845 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001846
1847 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001849
1850 ASSERT_EQ(OK, trust(&client, validServer));
1851 ASSERT_EQ(OK, trust(validServer, &client));
1852 ASSERT_EQ(OK, trust(maliciousServer, &client));
1853
1854 maliciousServer->start();
1855
1856 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1857 // the client can't verify the server's identity.
1858 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1859 client.run(handshakeOk);
1860}
1861
1862TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001863 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1864 (void)serverVersion;
1865
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001866 auto server = std::make_unique<Server>();
1867 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001868
1869 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001870 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871
1872 ASSERT_EQ(OK, trust(&client, server));
1873
1874 server->start();
1875
1876 // For TLS, Client should be able to verify server's identity, so client should see
1877 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1878 // identity and should drop the connection, so client shouldn't be able to read anything.
1879 bool readOk = rpcSecurity != RpcSecurity::TLS;
1880 client.run(true, readOk);
1881}
1882
1883TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001884 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1885 (void)serverVersion;
1886
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001887 auto server = std::make_unique<Server>();
1888 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001889
1890 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001891 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001892 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001893 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001894
1895 ASSERT_EQ(OK, trust(&validClient, server));
1896 ASSERT_EQ(OK, trust(&maliciousClient, server));
1897
1898 server->start();
1899
1900 // See UntrustedClient.
1901 bool readOk = rpcSecurity != RpcSecurity::TLS;
1902 maliciousClient.run(true, readOk);
1903}
1904
Yifan Hong67519322021-09-13 18:51:16 -07001905TEST_P(RpcTransportTest, Trigger) {
1906 std::string msg2 = ", world!";
1907 std::mutex writeMutex;
1908 std::condition_variable writeCv;
1909 bool shouldContinueWriting = false;
1910 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001911 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001912 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001913 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1914 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001915 if (status != OK) return AssertionFailure() << statusToString(status);
1916
1917 {
1918 std::unique_lock<std::mutex> lock(writeMutex);
1919 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1920 return AssertionFailure() << "write barrier not cleared in time!";
1921 }
1922 }
1923
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001924 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001925 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1926 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001927 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001928 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001929 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001930 << statusToString(status);
1931 return AssertionSuccess();
1932 };
1933
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001934 auto server = std::make_unique<Server>();
1935 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001936
1937 // Set up client
1938 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001939 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001940
1941 // Exchange keys
1942 ASSERT_EQ(OK, trust(&client, server));
1943 ASSERT_EQ(OK, trust(server, &client));
1944
1945 server->setPostConnect(serverPostConnect);
1946
Yifan Hong67519322021-09-13 18:51:16 -07001947 server->start();
1948 // connect() to server and do handshake
1949 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001950 // read the first message. This ensures that server has finished handshake and start handling
1951 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001952 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001953 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1954 // write is on an FdTrigger that has been shut down.
1955 server->shutdown();
1956 // Continues server thread to write the second message.
1957 {
Yifan Hong22211f82021-09-14 12:32:25 -07001958 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001959 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001960 }
Yifan Hong22211f82021-09-14 12:32:25 -07001961 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001962 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001963 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001964 // On the client side, second read fails with DEAD_OBJECT
1965 ASSERT_FALSE(client.readMessage(msg2));
1966}
1967
Pawan49d74cb2022-08-03 21:19:11 +00001968TEST_P(RpcTransportTest, CheckWaitingForRead) {
1969 std::mutex readMutex;
1970 std::condition_variable readCv;
1971 bool shouldContinueReading = false;
1972 // Server will write data on transport once its started
1973 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1974 std::string message(RpcTransportTestUtils::kMessage);
1975 iovec messageIov{message.data(), message.size()};
1976 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1977 std::nullopt, nullptr);
1978 if (status != OK) return AssertionFailure() << statusToString(status);
1979
1980 {
1981 std::unique_lock<std::mutex> lock(readMutex);
1982 shouldContinueReading = true;
1983 lock.unlock();
1984 readCv.notify_all();
1985 }
1986 return AssertionSuccess();
1987 };
1988
1989 // Setup Server and client
1990 auto server = std::make_unique<Server>();
1991 ASSERT_TRUE(server->setUp(GetParam()));
1992
1993 Client client(server->getConnectToServerFn());
1994 ASSERT_TRUE(client.setUp(GetParam()));
1995
1996 ASSERT_EQ(OK, trust(&client, server));
1997 ASSERT_EQ(OK, trust(server, &client));
1998 server->setPostConnect(serverPostConnect);
1999
2000 server->start();
2001 ASSERT_TRUE(client.setUpTransport());
2002 {
2003 // Wait till server writes data
2004 std::unique_lock<std::mutex> lock(readMutex);
2005 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2006 }
2007
2008 // Since there is no read polling here, we will get polling count 0
2009 ASSERT_FALSE(client.isTransportWaiting());
2010 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2011 // Thread should increment polling count, read and decrement polling count
2012 // Again, polling count should be zero here
2013 ASSERT_FALSE(client.isTransportWaiting());
2014
2015 server->shutdown();
2016}
2017
Yifan Hong1deca4b2021-09-10 16:16:44 -07002018INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002019 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002020 RpcTransportTest::PrintParamInfo);
2021
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002022class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002023 : public testing::TestWithParam<
2024 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025public:
2026 template <typename A, typename B>
2027 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002028 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2029 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002030 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2031 }
2032 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002033 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2034 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2035 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002036 };
2037};
2038
2039TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002040 if constexpr (!kEnableRpcThreads) {
2041 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2042 }
2043
Frederick Mayledc07cf82022-05-26 20:30:12 +00002044 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002045
2046 std::vector<uint8_t> pkeyData, certData;
2047 {
2048 auto pkey = makeKeyPairForSelfSignedCert();
2049 ASSERT_NE(nullptr, pkey);
2050 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2051 ASSERT_NE(nullptr, cert);
2052 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2053 certData = serializeCertificate(cert.get(), certificateFormat);
2054 }
2055
2056 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2057 auto desCert = deserializeCertificate(certData, certificateFormat);
2058 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002059 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2060 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002061
2062 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2063 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2064
2065 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2066 ASSERT_TRUE(client.setUp(utilsParam));
2067
2068 ASSERT_EQ(OK, trust(&client, server));
2069 ASSERT_EQ(OK, trust(server, &client));
2070
2071 server->start();
2072 client.run();
2073}
2074
2075INSTANTIATE_TEST_CASE_P(
2076 BinderRpc, RpcTransportTlsKeyTest,
2077 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2078 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002079 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2080 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002081 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002082#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002083
Steven Morelandc1635952021-04-01 16:20:47 +00002084} // namespace android
2085
2086int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002087 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002088 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002089
Steven Moreland5553ac42020-11-11 02:14:45 +00002090 return RUN_ALL_TESTS();
2091}