blob: bc34d4c36fadac059905abab74225c3bf975f6f9 [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
Andrei Homescu2a298012022-06-15 01:08:54 +000038#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000039#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000040
Yifan Hong1a235852021-05-13 16:07:47 -070041using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070042using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070043using testing::AssertionFailure;
44using testing::AssertionResult;
45using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070046
Steven Moreland5553ac42020-11-11 02:14:45 +000047namespace android {
48
Andrei Homescu12106de2022-04-27 04:42:21 +000049#ifdef BINDER_TEST_NO_SHARED_LIBS
50constexpr bool kEnableSharedLibs = false;
51#else
52constexpr bool kEnableSharedLibs = true;
53#endif
54
Andrei Homescud65666d2023-03-03 07:28:02 +000055#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000056constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
57#endif
58
Frederick Maylea12b0962022-06-25 01:13:22 +000059static std::string WaitStatusToString(int wstatus) {
60 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000061 return std::format("exit status {}", WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000062 }
63 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000064 return std::format("term signal {}", WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000065 }
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000066 return std::format("unexpected state {}", wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000067}
68
Steven Moreland276d8df2022-09-28 23:56:39 +000069static void debugBacktrace(pid_t pid) {
70 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
71 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
72}
73
Steven Moreland5553ac42020-11-11 02:14:45 +000074class Process {
75public:
Andrei Homescu96834632022-10-14 00:49:49 +000076 Process(Process&& other)
77 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
78 mReadEnd(std::move(other.mReadEnd)),
79 mWriteEnd(std::move(other.mWriteEnd)) {
80 // The default move constructor doesn't clear mPid after moving it,
81 // which we need to do because the destructor checks for mPid!=0
82 mPid = other.mPid;
83 other.mPid = 0;
84 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070085 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
86 android::base::borrowed_fd /* readEnd */)>& f) {
87 android::base::unique_fd childWriteEnd;
88 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000089 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
90 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000091 if (0 == (mPid = fork())) {
92 // racey: assume parent doesn't crash before this is set
93 prctl(PR_SET_PDEATHSIG, SIGHUP);
94
Yifan Hong1deca4b2021-09-10 16:16:44 -070095 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000096
97 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000098 }
99 }
100 ~Process() {
101 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000102 int wstatus;
103 waitpid(mPid, &wstatus, 0);
104 if (mCustomExitStatusCheck) {
105 mCustomExitStatusCheck(wstatus);
106 } else {
107 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
108 << "server process failed: " << WaitStatusToString(wstatus);
109 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000110 }
111 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700112 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700113 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000114
Frederick Maylea12b0962022-06-25 01:13:22 +0000115 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
116 mCustomExitStatusCheck = std::move(f);
117 }
118
Frederick Mayle69a0c992022-05-26 20:38:39 +0000119 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
120 void terminate() { kill(mPid, SIGTERM); }
121
Steven Moreland276d8df2022-09-28 23:56:39 +0000122 pid_t getPid() { return mPid; }
123
Steven Moreland5553ac42020-11-11 02:14:45 +0000124private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000125 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000126 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700127 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700128 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000129};
130
131static std::string allocateSocketAddress() {
132 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000133 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000134 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700135 unlink(ret.c_str());
136 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000137};
138
Steven Morelandda573042021-06-12 01:13:45 +0000139static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000140 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000141 return vsockPort++;
142}
143
Alice Wang893a9912022-10-24 10:44:09 +0000144static base::unique_fd initUnixSocket(std::string addr) {
145 auto socket_addr = UnixSocketAddress(addr.c_str());
146 base::unique_fd fd(
147 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
148 CHECK(fd.ok());
149 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
150 return fd;
151}
152
Andrei Homescu96834632022-10-14 00:49:49 +0000153// Destructors need to be defined, even if pure virtual
154ProcessSession::~ProcessSession() {}
155
156class LinuxProcessSession : public ProcessSession {
157public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000158 // reference to process hosting a socket server
159 Process host;
160
Andrei Homescu96834632022-10-14 00:49:49 +0000161 LinuxProcessSession(LinuxProcessSession&&) = default;
162 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
163 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 for (auto& session : sessions) {
165 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000166 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000167
Steven Moreland67f85902023-03-15 01:13:49 +0000168 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
169 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000171
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000172 EXPECT_NE(nullptr, session);
173 EXPECT_NE(nullptr, session->state());
174 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000175
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000176 wp<RpcSession> weakSession = session;
177 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000178
Steven Moreland57042712022-10-04 23:56:45 +0000179 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
180 // the object should not actually be promotable. By looping, we distinguish a race here
181 // from a bug causing the object to not be promotable.
182 for (size_t i = 0; i < 3; i++) {
183 sp<RpcSession> strongSession = weakSession.promote();
184 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000185 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000186 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
187 "Leaked sess: ")
188 << strongSession->getStrongCount() << " checked time " << i;
189
190 if (strongSession != nullptr) {
191 sleep(1);
192 }
193 }
Steven Moreland736664b2021-05-01 04:27:25 +0000194 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000195 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000196
Andrei Homescu96834632022-10-14 00:49:49 +0000197 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
198 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 }
Andrei Homescu96834632022-10-14 00:49:49 +0000200
201 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000202};
203
Yifan Hong1deca4b2021-09-10 16:16:44 -0700204static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700205 base::unique_fd serverFd(
206 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
207 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700208 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
209 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700210
211 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
212 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700213 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
214 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700215 }
216 return serverFd;
217}
218
Andrei Homescud65666d2023-03-03 07:28:02 +0000219#ifndef BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100220static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
221 base::unique_fd sockClient, sockServer;
222 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
223 int savedErrno = errno;
224 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
225 }
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) {
David Brazdil21c887c2022-09-23 12:25:18 +0100233 int savedErrno = errno;
234 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
235 }
236 return std::move(sockClient);
237}
Andrei Homescud65666d2023-03-03 07:28:02 +0000238#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100239
Andrei Homescuf30148c2023-03-10 00:31:45 +0000240std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
241 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000242}
Andrei Homescu2a298012022-06-15 01:08:54 +0000243
Andrei Homescu96834632022-10-14 00:49:49 +0000244// This creates a new process serving an interface on a certain number of
245// threads.
246std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
247 const BinderRpcOptions& options) {
248 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000249
Steven Moreland67f85902023-03-15 01:13:49 +0000250 if (options.numIncomingConnectionsBySession.size() != 0) {
251 CHECK_EQ(options.numIncomingConnectionsBySession.size(), options.numSessions);
252 }
253
Steven Morelandb469f432023-07-28 22:13:47 +0000254 SocketType socketType = GetParam().type;
255 RpcSecurity rpcSecurity = GetParam().security;
256 uint32_t clientVersion = GetParam().clientVersion;
257 uint32_t serverVersion = GetParam().serverVersion;
258 bool singleThreaded = GetParam().singleThreaded;
259 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000260
261 std::string path = android::base::GetExecutableDirectory();
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000262 auto servicePath =
263 std::format("{}/binder_rpc_test_service{}{}", path,
264 singleThreaded ? "_single_threaded" : "", noKernel ? "_no_kernel" : "");
Andrei Homescu96834632022-10-14 00:49:49 +0000265
Alice Wang1ef010b2022-11-14 09:09:25 +0000266 base::unique_fd bootstrapClientFd, socketFd;
267
Alice Wang893a9912022-10-24 10:44:09 +0000268 auto addr = allocateSocketAddress();
269 // Initializes the socket before the fork/exec.
270 if (socketType == SocketType::UNIX_RAW) {
271 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000272 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
273 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
274 // This is because we cannot pass ParcelFileDescriptor over a pipe.
275 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
276 int savedErrno = errno;
277 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
278 }
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());
290 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
291 NULL);
292 }));
293
294 BinderRpcTestServerConfig serverConfig;
295 serverConfig.numThreads = options.numThreads;
296 serverConfig.socketType = static_cast<int32_t>(socketType);
297 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
298 serverConfig.serverVersion = serverVersion;
299 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000300 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000301 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000302 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
303 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
304 static_cast<int32_t>(mode));
305 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000306 if (socketType != SocketType::TIPC) {
307 writeToFd(ret->host.writeEnd(), serverConfig);
308 }
Andrei Homescu96834632022-10-14 00:49:49 +0000309
310 std::vector<sp<RpcSession>> sessions;
311 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
312 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000313 std::unique_ptr<RpcTransportCtxFactory> factory;
314 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000315#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000316 factory = RpcTransportCtxFactoryTipcAndroid::make();
317#else
318 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
319#endif
320 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000321 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000322 }
323 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100324 }
325
Andrei Homescu68a55612022-08-02 01:25:15 +0000326 BinderRpcTestServerInfo serverInfo;
327 if (socketType != SocketType::TIPC) {
328 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
329 BinderRpcTestClientInfo clientInfo;
330 for (const auto& session : sessions) {
331 auto& parcelableCert = clientInfo.certs.emplace_back();
332 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
333 }
334 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000335
Andrei Homescu68a55612022-08-02 01:25:15 +0000336 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
337 if (socketType == SocketType::INET) {
338 CHECK_NE(0, serverInfo.port);
339 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000340
Andrei Homescu68a55612022-08-02 01:25:15 +0000341 if (rpcSecurity == RpcSecurity::TLS) {
342 const auto& serverCert = serverInfo.cert.data;
343 CHECK_EQ(OK,
344 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
345 serverCert));
346 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700347 }
348
Andrei Homescu96834632022-10-14 00:49:49 +0000349 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000350
Steven Moreland67f85902023-03-15 01:13:49 +0000351 for (size_t i = 0; i < sessions.size(); i++) {
352 const auto& session = sessions.at(i);
353
354 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
355 ? options.numIncomingConnectionsBySession.at(i)
356 : 0;
357
Andrei Homescu96834632022-10-14 00:49:49 +0000358 CHECK(session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000359 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000360 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000361 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000362
Andrei Homescu96834632022-10-14 00:49:49 +0000363 switch (socketType) {
364 case SocketType::PRECONNECTED:
365 status = session->setupPreconnectedClient({}, [=]() {
366 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
367 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000368 break;
Alice Wang893a9912022-10-24 10:44:09 +0000369 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000370 case SocketType::UNIX:
371 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
372 break;
373 case SocketType::UNIX_BOOTSTRAP:
374 status = session->setupUnixDomainSocketBootstrapClient(
375 base::unique_fd(dup(bootstrapClientFd.get())));
376 break;
377 case SocketType::VSOCK:
378 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
379 break;
380 case SocketType::INET:
381 status = session->setupInetClient("127.0.0.1", serverInfo.port);
382 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000383 case SocketType::TIPC:
384 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000385#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000386 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000387 for (size_t i = 0; i < 5; i++) {
388 // Try to connect several times,
389 // in case the service is slow to start
390 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
391 if (tipcFd >= 0) {
392 return android::base::unique_fd(tipcFd);
393 }
394 usleep(50000);
395 }
396 return android::base::unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000397#else
398 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
399 return android::base::unique_fd();
400#endif
401 });
402 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000403 default:
404 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000405 }
Andrei Homescu96834632022-10-14 00:49:49 +0000406 if (options.allowConnectFailure && status != OK) {
407 ret->sessions.clear();
408 break;
409 }
410 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
411 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000412 }
Andrei Homescu96834632022-10-14 00:49:49 +0000413 return ret;
414}
Steven Morelandc1635952021-04-01 16:20:47 +0000415
Andrei Homescua858b0e2022-08-01 23:43:09 +0000416TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
417 if (clientOrServerSingleThreaded()) {
418 GTEST_SKIP() << "This test requires multiple threads";
419 }
420
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 constexpr size_t kNumThreads = 10;
422
Steven Moreland4313d7e2021-07-15 23:41:22 +0000423 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000424
425 EXPECT_OK(proc.rootIface->lock());
426
427 // block all but one thread taking locks
428 std::vector<std::thread> ts;
429 for (size_t i = 0; i < kNumThreads - 1; i++) {
430 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
431 }
432
Steven Morelandd6d816f2022-12-23 01:37:17 +0000433 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000434
435 // other calls still work
436 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
437
Steven Morelandd6d816f2022-12-23 01:37:17 +0000438 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 size_t epochMsBefore = epochMillis();
440 // after this, we should never see a response within this time
441 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
442
443 // this call should be blocked for blockTimeMs
444 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
445
446 size_t epochMsAfter = epochMillis();
447 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
448
449 for (auto& t : ts) t.join();
450}
451
Steven Moreland27f620a2023-03-06 19:44:36 +0000452static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000453 size_t epochMsBefore = epochMillis();
454
455 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700456 for (size_t i = 0; i < numCalls; i++) {
457 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000458 }
459
460 for (auto& t : ts) t.join();
461
462 size_t epochMsAfter = epochMillis();
463
Yifan Hong1f44f982021-10-08 17:16:47 -0700464 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000465
Steven Moreland9c203222023-05-31 21:26:41 +0000466 // Potential flake, but make sure calls are handled in parallel. Due
467 // to past flakes, this only checks that the amount of time taken has
468 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
469 // check this more exactly.
470 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700471}
472
Andrei Homescua858b0e2022-08-01 23:43:09 +0000473TEST_P(BinderRpc, ThreadPoolOverSaturated) {
474 if (clientOrServerSingleThreaded()) {
475 GTEST_SKIP() << "This test requires multiple threads";
476 }
477
Yifan Hong1f44f982021-10-08 17:16:47 -0700478 constexpr size_t kNumThreads = 10;
479 constexpr size_t kNumCalls = kNumThreads + 3;
480 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000481
482 // b/272429574 - below 500ms, the test fails
483 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700484}
485
Andrei Homescua858b0e2022-08-01 23:43:09 +0000486TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
487 if (clientOrServerSingleThreaded()) {
488 GTEST_SKIP() << "This test requires multiple threads";
489 }
490
Yifan Hong1f44f982021-10-08 17:16:47 -0700491 constexpr size_t kNumThreads = 20;
492 constexpr size_t kNumOutgoingConnections = 10;
493 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
494 auto proc = createRpcTestSocketServerProcess(
495 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000496
497 // b/272429574 - below 500ms, the test fails
498 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000499}
500
Andrei Homescua858b0e2022-08-01 23:43:09 +0000501TEST_P(BinderRpc, ThreadingStressTest) {
502 if (clientOrServerSingleThreaded()) {
503 GTEST_SKIP() << "This test requires multiple threads";
504 }
505
Steven Moreland27f620a2023-03-06 19:44:36 +0000506 constexpr size_t kNumClientThreads = 5;
507 constexpr size_t kNumServerThreads = 5;
508 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000509
Steven Moreland4313d7e2021-07-15 23:41:22 +0000510 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000511
512 std::vector<std::thread> threads;
513 for (size_t i = 0; i < kNumClientThreads; i++) {
514 threads.push_back(std::thread([&] {
515 for (size_t j = 0; j < kNumCalls; j++) {
516 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000517 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000518 EXPECT_EQ(proc.rootBinder, out);
519 }
520 }));
521 }
522
523 for (auto& t : threads) t.join();
524}
525
Steven Moreland925ba0a2021-09-17 18:06:32 -0700526static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
527 std::vector<std::thread> threads;
528 for (size_t i = 0; i < threadCount; i++) {
529 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
530 }
531 for (auto& t : threads) t.join();
532}
533
Andrei Homescua858b0e2022-08-01 23:43:09 +0000534TEST_P(BinderRpc, OnewayStressTest) {
535 if (clientOrServerSingleThreaded()) {
536 GTEST_SKIP() << "This test requires multiple threads";
537 }
538
Steven Morelandc6046982021-04-20 00:49:42 +0000539 constexpr size_t kNumClientThreads = 10;
540 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700541 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000542
Steven Moreland4313d7e2021-07-15 23:41:22 +0000543 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000544
545 std::vector<std::thread> threads;
546 for (size_t i = 0; i < kNumClientThreads; i++) {
547 threads.push_back(std::thread([&] {
548 for (size_t j = 0; j < kNumCalls; j++) {
549 EXPECT_OK(proc.rootIface->sendString("a"));
550 }
Steven Morelandc6046982021-04-20 00:49:42 +0000551 }));
552 }
553
554 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700555
556 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000557}
558
Frederick Mayleb0221d12022-10-03 23:10:53 +0000559TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
560 if (!supportsFdTransport()) {
561 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
562 }
563 if (clientOrServerSingleThreaded()) {
564 GTEST_SKIP() << "This test requires multiple threads";
565 }
566
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000567 constexpr size_t kNumServerThreads = 3;
568
Frederick Mayleb0221d12022-10-03 23:10:53 +0000569 // This test forces a oneway transaction to be queued by issuing two
570 // `blockingSendFdOneway` calls, then drains the queue by issuing two
571 // `blockingRecvFd` calls.
572 //
573 // For more details about the queuing semantics see
574 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
575
576 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000577 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000578 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
579 .serverSupportedFileDescriptorTransportModes =
580 {RpcSession::FileDescriptorTransportMode::UNIX},
581 });
582
583 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
584 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
585 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
586 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
587
588 android::os::ParcelFileDescriptor fdA;
589 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
590 std::string result;
591 CHECK(android::base::ReadFdToString(fdA.get(), &result));
592 EXPECT_EQ(result, "a");
593
594 android::os::ParcelFileDescriptor fdB;
595 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
596 CHECK(android::base::ReadFdToString(fdB.get(), &result));
597 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000598
599 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000600}
601
Andrei Homescua858b0e2022-08-01 23:43:09 +0000602TEST_P(BinderRpc, OnewayCallQueueing) {
603 if (clientOrServerSingleThreaded()) {
604 GTEST_SKIP() << "This test requires multiple threads";
605 }
606
Frederick Mayle96872592023-03-07 14:56:15 -0800607 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000609
610 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000611 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000612
Frederick Mayle96872592023-03-07 14:56:15 -0800613 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700614 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800615 for (size_t i = 0; i + 1 < kNumQueued; i++) {
616 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000617 }
Frederick Mayle96872592023-03-07 14:56:15 -0800618 for (size_t i = 0; i + 1 < kNumQueued; i++) {
619 int n;
620 proc.rootIface->blockingRecvInt(&n);
621 EXPECT_EQ(n, i);
622 }
Steven Morelandf5174272021-05-25 00:39:28 +0000623
Steven Moreland925ba0a2021-09-17 18:06:32 -0700624 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000625}
626
Andrei Homescua858b0e2022-08-01 23:43:09 +0000627TEST_P(BinderRpc, OnewayCallExhaustion) {
628 if (clientOrServerSingleThreaded()) {
629 GTEST_SKIP() << "This test requires multiple threads";
630 }
631
Steven Morelandd45be622021-06-04 02:19:37 +0000632 constexpr size_t kNumClients = 2;
633 constexpr size_t kTooLongMs = 1000;
634
Steven Moreland4313d7e2021-07-15 23:41:22 +0000635 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000636
637 // Build up oneway calls on the second session to make sure it terminates
638 // and shuts down. The first session should be unaffected (proc destructor
639 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000640 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000641
642 std::vector<std::thread> threads;
643 for (size_t i = 0; i < kNumClients; i++) {
644 // one of these threads will get stuck queueing a transaction once the
645 // socket fills up, the other will be able to fill up transactions on
646 // this object
647 threads.push_back(std::thread([&] {
648 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
649 }
650 }));
651 }
652 for (auto& t : threads) t.join();
653
654 Status status = iface->sleepMsAsync(kTooLongMs);
655 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
656
Steven Moreland798e0d12021-07-14 23:19:25 +0000657 // now that it has died, wait for the remote session to shutdown
658 std::vector<int32_t> remoteCounts;
659 do {
660 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
661 } while (remoteCounts.size() == kNumClients);
662
Steven Morelandd45be622021-06-04 02:19:37 +0000663 // the second session should be shutdown in the other process by the time we
664 // are able to join above (it'll only be hung up once it finishes processing
665 // any pending commands). We need to erase this session from the record
666 // here, so that the destructor for our session won't check that this
667 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000668 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000669}
670
Steven Moreland67f85902023-03-15 01:13:49 +0000671TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
672 if (clientOrServerSingleThreaded()) {
673 GTEST_SKIP() << "This test requires multiple threads";
674 }
675
676 // session 0 - will check for leaks in destrutor of proc
677 // session 1 - we want to make sure it gets deleted when we drop all references to it
678 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700679 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000680
681 wp<RpcSession> session = proc.proc->sessions.at(1).session;
682
683 // remove all references to the second session
684 proc.proc->sessions.at(1).root = nullptr;
685 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
686
687 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
688 // to drain commands.
689 for (size_t i = 0; i < 100; i++) {
690 usleep(10 * 1000);
691 if (session.promote() == nullptr) break;
692 }
693
694 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000695
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000696 // now that it has died, wait for the remote session to shutdown
697 std::vector<int32_t> remoteCounts;
698 do {
699 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
700 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000701}
702
Devin Moore66d5b7a2022-07-07 21:42:10 +0000703TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000704 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000705 GTEST_SKIP() << "This test requires multiple threads";
706 }
707 class MyDeathRec : public IBinder::DeathRecipient {
708 public:
709 void binderDied(const wp<IBinder>& /* who */) override {
710 dead = true;
711 mCv.notify_one();
712 }
713 std::mutex mMtx;
714 std::condition_variable mCv;
715 bool dead = false;
716 };
717
718 // Death recipient needs to have an incoming connection to be called
719 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000720 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000721
722 auto dr = sp<MyDeathRec>::make();
723 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
724
725 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
726 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
727 }
728
729 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000730 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000731
732 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000733 // can't do this before checking the death recipient by calling
734 // forceShutdown earlier, because shutdownAndWait will also trigger
735 // a death recipient, but if we had a way to wait for the service
736 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000737 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000738 proc.expectAlreadyShutdown = true;
739}
740
741TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000742 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000743 GTEST_SKIP() << "This test requires multiple threads";
744 }
745 class MyDeathRec : public IBinder::DeathRecipient {
746 public:
747 void binderDied(const wp<IBinder>& /* who */) override {
748 dead = true;
749 mCv.notify_one();
750 }
751 std::mutex mMtx;
752 std::condition_variable mCv;
753 bool dead = false;
754 };
755
756 // Death recipient needs to have an incoming connection to be called
757 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000758 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000759
760 auto dr = sp<MyDeathRec>::make();
761 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
762
763 // Explicitly calling shutDownAndWait will cause the death recipients
764 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000765 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000766
767 std::unique_lock<std::mutex> lock(dr->mMtx);
768 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000769 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000770 }
771 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
772
Andrei Homescu96834632022-10-14 00:49:49 +0000773 proc.proc->terminate();
774 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000775 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
776 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
777 });
778 proc.expectAlreadyShutdown = true;
779}
780
Steven Moreland5ec743f2023-01-18 01:02:06 +0000781TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000782 if (socketType() == SocketType::TIPC) {
783 // This should work, but Trusty takes too long to restart the service
784 GTEST_SKIP() << "Service death test not supported on Trusty";
785 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000786 class MyDeathRec : public IBinder::DeathRecipient {
787 public:
788 void binderDied(const wp<IBinder>& /* who */) override {}
789 };
790
Steven Moreland67f85902023-03-15 01:13:49 +0000791 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000792
793 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000794 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000795}
796
797TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000798 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000799 GTEST_SKIP() << "This test requires multiple threads";
800 }
801 class MyDeathRec : public IBinder::DeathRecipient {
802 public:
803 void binderDied(const wp<IBinder>& /* who */) override {
804 GTEST_FAIL() << "This should not be called after unlinkToDeath";
805 }
806 };
807
808 // Death recipient needs to have an incoming connection to be called
809 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000810 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000811
812 auto dr = sp<MyDeathRec>::make();
813 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
814 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
815
Steven Moreland67f85902023-03-15 01:13:49 +0000816 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000817}
818
Steven Morelandc1635952021-04-01 16:20:47 +0000819TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000820 if (socketType() == SocketType::TIPC) {
821 // This should work, but Trusty takes too long to restart the service
822 GTEST_SKIP() << "Service death test not supported on Trusty";
823 }
824
Steven Moreland5553ac42020-11-11 02:14:45 +0000825 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000826 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000827
828 // make sure there is some state during crash
829 // 1. we hold their binder
830 sp<IBinderRpcSession> session;
831 EXPECT_OK(proc.rootIface->openSession("happy", &session));
832 // 2. they hold our binder
833 sp<IBinder> binder = new BBinder();
834 EXPECT_OK(proc.rootIface->holdBinder(binder));
835
836 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
837 << "Do death cleanup: " << doDeathCleanup;
838
Andrei Homescu96834632022-10-14 00:49:49 +0000839 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000840 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
841 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
842 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000843 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000844 }
845}
846
Steven Morelandd7302072021-05-15 01:32:04 +0000847TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000848 // This test only works if the current process shared the internal state of
849 // ProcessState with the service across the call to fork(). Both the static
850 // libraries and libbinder.so have their own separate copies of all the
851 // globals, so the test only works when the test client and service both use
852 // libbinder.so (when using static libraries, even a client and service
853 // using the same kind of static library should have separate copies of the
854 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000855 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000856 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
857 "at build time.";
858 }
859
Steven Moreland4313d7e2021-07-15 23:41:22 +0000860 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000861
Andrei Homescu2a298012022-06-15 01:08:54 +0000862 // we can't allocate IPCThreadState so actually the first time should
863 // succeed :(
864 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000865
866 // second time! we catch the error :)
867 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
868
Andrei Homescu96834632022-10-14 00:49:49 +0000869 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000870 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
871 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
872 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000873 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000874}
875
Frederick Mayle69a0c992022-05-26 20:38:39 +0000876TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000877 if (socketType() == SocketType::TIPC) {
878 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
879 }
880
Frederick Mayle69a0c992022-05-26 20:38:39 +0000881 auto proc = createRpcTestSocketServerProcess({
882 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
883 .serverSupportedFileDescriptorTransportModes =
884 {RpcSession::FileDescriptorTransportMode::UNIX},
885 .allowConnectFailure = true,
886 });
Andrei Homescu96834632022-10-14 00:49:49 +0000887 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
888 proc.proc->terminate();
889 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000890 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
891 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
892 });
893 proc.expectAlreadyShutdown = true;
894}
895
896TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000897 if (socketType() == SocketType::TIPC) {
898 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
899 }
900
Frederick Mayle69a0c992022-05-26 20:38:39 +0000901 auto proc = createRpcTestSocketServerProcess({
902 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
903 .serverSupportedFileDescriptorTransportModes =
904 {RpcSession::FileDescriptorTransportMode::NONE},
905 .allowConnectFailure = true,
906 });
Andrei Homescu96834632022-10-14 00:49:49 +0000907 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
908 proc.proc->terminate();
909 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000910 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
911 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
912 });
913 proc.expectAlreadyShutdown = true;
914}
915
916TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000917 if (socketType() == SocketType::TIPC) {
918 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
919 }
920
Frederick Mayle69a0c992022-05-26 20:38:39 +0000921 auto proc = createRpcTestSocketServerProcess({
922 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
923 .serverSupportedFileDescriptorTransportModes =
924 {RpcSession::FileDescriptorTransportMode::NONE,
925 RpcSession::FileDescriptorTransportMode::UNIX},
926 });
927
928 android::os::ParcelFileDescriptor out;
929 auto status = proc.rootIface->echoAsFile("hello", &out);
930 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
931}
932
933TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000934 if (socketType() == SocketType::TIPC) {
935 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
936 }
937
Frederick Mayle69a0c992022-05-26 20:38:39 +0000938 auto proc = createRpcTestSocketServerProcess({
939 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
940 .serverSupportedFileDescriptorTransportModes =
941 {RpcSession::FileDescriptorTransportMode::UNIX},
942 });
943
944 android::os::ParcelFileDescriptor out;
945 auto status = proc.rootIface->echoAsFile("hello", &out);
946 if (!supportsFdTransport()) {
947 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
948 return;
949 }
950 ASSERT_TRUE(status.isOk()) << status;
951
952 std::string result;
953 CHECK(android::base::ReadFdToString(out.get(), &result));
954 EXPECT_EQ(result, "hello");
955}
956
957TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000958 if (socketType() == SocketType::TIPC) {
959 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
960 }
961
Frederick Mayle69a0c992022-05-26 20:38:39 +0000962 auto proc = createRpcTestSocketServerProcess({
963 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
964 .serverSupportedFileDescriptorTransportModes =
965 {RpcSession::FileDescriptorTransportMode::UNIX},
966 });
967
968 std::vector<android::os::ParcelFileDescriptor> files;
969 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
970 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
971 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
972 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
973
974 android::os::ParcelFileDescriptor out;
975 auto status = proc.rootIface->concatFiles(files, &out);
976 if (!supportsFdTransport()) {
977 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
978 return;
979 }
980 ASSERT_TRUE(status.isOk()) << status;
981
982 std::string result;
983 CHECK(android::base::ReadFdToString(out.get(), &result));
984 EXPECT_EQ(result, "123abcd");
985}
986
987TEST_P(BinderRpc, SendMaxFiles) {
988 if (!supportsFdTransport()) {
989 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
990 }
991
992 auto proc = createRpcTestSocketServerProcess({
993 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
994 .serverSupportedFileDescriptorTransportModes =
995 {RpcSession::FileDescriptorTransportMode::UNIX},
996 });
997
998 std::vector<android::os::ParcelFileDescriptor> files;
999 for (int i = 0; i < 253; i++) {
1000 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1001 }
1002
1003 android::os::ParcelFileDescriptor out;
1004 auto status = proc.rootIface->concatFiles(files, &out);
1005 ASSERT_TRUE(status.isOk()) << status;
1006
1007 std::string result;
1008 CHECK(android::base::ReadFdToString(out.get(), &result));
1009 EXPECT_EQ(result, std::string(253, 'a'));
1010}
1011
1012TEST_P(BinderRpc, SendTooManyFiles) {
1013 if (!supportsFdTransport()) {
1014 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1015 }
1016
1017 auto proc = createRpcTestSocketServerProcess({
1018 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1019 .serverSupportedFileDescriptorTransportModes =
1020 {RpcSession::FileDescriptorTransportMode::UNIX},
1021 });
1022
1023 std::vector<android::os::ParcelFileDescriptor> files;
1024 for (int i = 0; i < 254; i++) {
1025 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1026 }
1027
1028 android::os::ParcelFileDescriptor out;
1029 auto status = proc.rootIface->concatFiles(files, &out);
1030 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1031}
1032
Andrei Homescufc221502022-10-08 03:51:17 +00001033TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001034 if (socketType() == SocketType::TIPC) {
1035 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1036 }
1037
Andrei Homescufc221502022-10-08 03:51:17 +00001038 auto proc = createRpcTestSocketServerProcess({
1039 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1040 .serverSupportedFileDescriptorTransportModes =
1041 {RpcSession::FileDescriptorTransportMode::UNIX},
1042 });
1043
1044 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1045 ASSERT_NE(badFd, -1);
1046
1047 // Close the file descriptor so it becomes invalid for dup
1048 close(badFd);
1049
1050 Parcel p1;
1051 p1.markForBinder(proc.rootBinder);
1052 p1.writeInt32(3);
1053 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1054
1055 Parcel pRaw;
1056 pRaw.markForBinder(proc.rootBinder);
1057 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1058
1059 pRaw.setDataPosition(0);
1060 EXPECT_EQ(3, pRaw.readInt32());
1061 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1062}
1063
Andrei Homescu68a55612022-08-02 01:25:15 +00001064#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001065TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001066 if constexpr (!kEnableSharedLibs) {
1067 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1068 }
1069
Steven Moreland4313d7e2021-07-15 23:41:22 +00001070 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001071
1072 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1073 ASSERT_NE(binder, nullptr);
1074
1075 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1076}
1077
1078TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001079 if constexpr (!kEnableSharedLibs) {
1080 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1081 }
1082
Steven Moreland4313d7e2021-07-15 23:41:22 +00001083 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001084
1085 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1086 ASSERT_NE(binder, nullptr);
1087
1088 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1089 ASSERT_NE(ndkBinder, nullptr);
1090
1091 std::string out;
1092 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1093 ASSERT_TRUE(status.isOk()) << status.getDescription();
1094 ASSERT_EQ("aoeuaoeu", out);
1095}
Andrei Homescu68a55612022-08-02 01:25:15 +00001096#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001097
Steven Moreland5553ac42020-11-11 02:14:45 +00001098ssize_t countFds() {
1099 DIR* dir = opendir("/proc/self/fd/");
1100 if (dir == nullptr) return -1;
1101 ssize_t ret = 0;
1102 dirent* ent;
1103 while ((ent = readdir(dir)) != nullptr) ret++;
1104 closedir(dir);
1105 return ret;
1106}
1107
Andrei Homescua858b0e2022-08-01 23:43:09 +00001108TEST_P(BinderRpc, Fds) {
1109 if (serverSingleThreaded()) {
1110 GTEST_SKIP() << "This test requires multiple threads";
1111 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001112 if (socketType() == SocketType::TIPC) {
1113 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1114 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001115
Steven Moreland5553ac42020-11-11 02:14:45 +00001116 ssize_t beforeFds = countFds();
1117 ASSERT_GE(beforeFds, 0);
1118 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001119 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001120 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1121 }
1122 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1123}
1124
Andrei Homescud65666d2023-03-03 07:28:02 +00001125#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001126
1127static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1128 std::vector<BinderRpc::ParamType> ret;
1129
1130 for (const auto& clientVersion : testVersions()) {
1131 for (const auto& serverVersion : testVersions()) {
1132 ret.push_back(BinderRpc::ParamType{
1133 .type = SocketType::TIPC,
1134 .security = RpcSecurity::RAW,
1135 .clientVersion = clientVersion,
1136 .serverVersion = serverVersion,
1137 .singleThreaded = true,
1138 .noKernel = true,
1139 });
1140 }
1141 }
1142
1143 return ret;
1144}
1145
1146INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
Andrei Homescud65666d2023-03-03 07:28:02 +00001147 BinderRpc::PrintParamInfo);
1148#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001149bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001150 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001151 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001152
Andrei Homescu992a4052022-06-28 21:26:18 +00001153 android::base::unique_fd serverFd(
1154 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001155
1156 if (errno == EAFNOSUPPORT) {
1157 return false;
1158 }
1159
Andrei Homescu992a4052022-06-28 21:26:18 +00001160 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1161
1162 sockaddr_vm serverAddr{
1163 .svm_family = AF_VSOCK,
1164 .svm_port = vsockPort,
1165 .svm_cid = VMADDR_CID_ANY,
1166 };
1167 int ret = TEMP_FAILURE_RETRY(
1168 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1169 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1170 strerror(errno));
1171
1172 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1173 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1174 strerror(errno));
1175
1176 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1177 // to see if the kernel supports it. It's safe to use a blocking
1178 // connect because vsock sockets have a 2 second connection timeout,
1179 // and they return ETIMEDOUT after that.
1180 android::base::unique_fd connectFd(
1181 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1182 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1183 strerror(errno));
1184
1185 bool success = false;
1186 sockaddr_vm connectAddr{
1187 .svm_family = AF_VSOCK,
1188 .svm_port = vsockPort,
1189 .svm_cid = VMADDR_CID_LOCAL,
1190 };
1191 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1192 sizeof(connectAddr)));
1193 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1194 android::base::unique_fd acceptFd;
1195 while (true) {
1196 pollfd pfd[]{
1197 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1198 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1199 };
1200 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1201 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1202
1203 if (pfd[0].revents & POLLIN) {
1204 sockaddr_vm acceptAddr;
1205 socklen_t acceptAddrLen = sizeof(acceptAddr);
1206 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1207 reinterpret_cast<sockaddr*>(&acceptAddr),
1208 &acceptAddrLen, SOCK_CLOEXEC));
1209 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1210 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1211 "Truncated address");
1212
1213 // Store the fd in acceptFd so we keep the connection alive
1214 // while polling connectFd
1215 acceptFd.reset(ret);
1216 }
1217
1218 if (pfd[1].revents & POLLOUT) {
1219 // Connect either succeeded or timed out
1220 int connectErrno;
1221 socklen_t connectErrnoLen = sizeof(connectErrno);
1222 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1223 &connectErrnoLen);
1224 LOG_ALWAYS_FATAL_IF(ret == -1,
1225 "Could not getsockopt() after connect() "
1226 "on non-blocking socket: %s.",
1227 strerror(errno));
1228
1229 // We're done, this is all we wanted
1230 success = connectErrno == 0;
1231 break;
1232 }
1233 }
1234 } else {
1235 success = ret == 0;
1236 }
1237
1238 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1239
1240 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001241}
1242
Yifan Hong1deca4b2021-09-10 16:16:44 -07001243static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001244 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1245 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001246
1247 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001248
Steven Moreland9f250b02023-05-16 23:27:42 +00001249#ifdef __BIONIC__
1250 // Devices may not have vsock support. AVF tests will verify whether they do, but
1251 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001252 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001253#else
1254 // On host machines, we always assume we have vsock loopback. If we don't, the
1255 // subsequent failures will be more clear than showing one now.
1256 static bool hasVsockLoopback = true;
1257#endif
Steven Morelandda573042021-06-12 01:13:45 +00001258
1259 if (hasVsockLoopback) {
1260 ret.push_back(SocketType::VSOCK);
1261 }
1262
1263 return ret;
1264}
1265
Steven Morelandb469f432023-07-28 22:13:47 +00001266static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1267 std::vector<BinderRpc::ParamType> ret;
1268
Steven Morelandf7421432023-07-28 22:41:44 +00001269 constexpr bool full = false;
1270
Steven Morelandb469f432023-07-28 22:13:47 +00001271 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001272 if (full || type == SocketType::UNIX) {
1273 for (const auto& security : RpcSecurityValues()) {
1274 for (const auto& clientVersion : testVersions()) {
1275 for (const auto& serverVersion : testVersions()) {
1276 for (bool singleThreaded : {false, true}) {
1277 for (bool noKernel : {false, true}) {
1278 ret.push_back(BinderRpc::ParamType{
1279 .type = type,
1280 .security = security,
1281 .clientVersion = clientVersion,
1282 .serverVersion = serverVersion,
1283 .singleThreaded = singleThreaded,
1284 .noKernel = noKernel,
1285 });
1286 }
Steven Morelandb469f432023-07-28 22:13:47 +00001287 }
1288 }
1289 }
1290 }
Steven Morelandf7421432023-07-28 22:41:44 +00001291 } else {
1292 ret.push_back(BinderRpc::ParamType{
1293 .type = type,
1294 .security = RpcSecurity::RAW,
1295 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1296 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1297 .singleThreaded = false,
1298 .noKernel = false,
1299 });
Steven Morelandb469f432023-07-28 22:13:47 +00001300 }
1301 }
Steven Morelandf7421432023-07-28 22:41:44 +00001302
Steven Morelandb469f432023-07-28 22:13:47 +00001303 return ret;
1304}
1305
1306INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
Yifan Hong702115c2021-06-24 15:39:18 -07001307 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001308
Yifan Hong702115c2021-06-24 15:39:18 -07001309class BinderRpcServerRootObject
1310 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001311
1312TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1313 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1314 auto setRootObject = [](bool isStrong) -> SetFn {
1315 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1316 };
1317
Yifan Hong702115c2021-06-24 15:39:18 -07001318 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001319 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001320 auto binder1 = sp<BBinder>::make();
1321 IBinder* binderRaw1 = binder1.get();
1322 setRootObject(isStrong1)(server.get(), binder1);
1323 EXPECT_EQ(binderRaw1, server->getRootObject());
1324 binder1.clear();
1325 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1326
1327 auto binder2 = sp<BBinder>::make();
1328 IBinder* binderRaw2 = binder2.get();
1329 setRootObject(isStrong2)(server.get(), binder2);
1330 EXPECT_EQ(binderRaw2, server->getRootObject());
1331 binder2.clear();
1332 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1333}
1334
1335INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001336 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1337 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001338
Yifan Hong1a235852021-05-13 16:07:47 -07001339class OneOffSignal {
1340public:
1341 // If notify() was previously called, or is called within |duration|, return true; else false.
1342 template <typename R, typename P>
1343 bool wait(std::chrono::duration<R, P> duration) {
1344 std::unique_lock<std::mutex> lock(mMutex);
1345 return mCv.wait_for(lock, duration, [this] { return mValue; });
1346 }
1347 void notify() {
1348 std::unique_lock<std::mutex> lock(mMutex);
1349 mValue = true;
1350 lock.unlock();
1351 mCv.notify_all();
1352 }
1353
1354private:
1355 std::mutex mMutex;
1356 std::condition_variable mCv;
1357 bool mValue = false;
1358};
1359
Yifan Hong194acf22021-06-29 18:44:56 -07001360TEST(BinderRpc, Java) {
1361#if !defined(__ANDROID__)
1362 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1363 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1364 "to binderHostDeviceTest. Hence, just disable this test on host.";
1365#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001366 if constexpr (!kEnableKernelIpc) {
1367 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1368 "at build time.";
1369 }
1370
Yifan Hong194acf22021-06-29 18:44:56 -07001371 sp<IServiceManager> sm = defaultServiceManager();
1372 ASSERT_NE(nullptr, sm);
1373 // Any Java service with non-empty getInterfaceDescriptor() would do.
1374 // Let's pick batteryproperties.
1375 auto binder = sm->checkService(String16("batteryproperties"));
1376 ASSERT_NE(nullptr, binder);
1377 auto descriptor = binder->getInterfaceDescriptor();
1378 ASSERT_GE(descriptor.size(), 0);
1379 ASSERT_EQ(OK, binder->pingBinder());
1380
1381 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001382 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001383 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001384 auto socket = rpcServer->releaseServer();
1385
1386 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001387 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1388
Yifan Honge3caaf22022-01-12 14:46:56 -08001389 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1390 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001391 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001392 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1393 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001394 << statusToString(setRpcClientDebugStatus);
1395 GTEST_SKIP();
1396 }
1397
1398 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001399
1400 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001401 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001402 auto rpcBinder = rpcSession->getRootObject();
1403 ASSERT_NE(nullptr, rpcBinder);
1404
1405 ASSERT_EQ(OK, rpcBinder->pingBinder());
1406
1407 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1408 << "getInterfaceDescriptor should not crash system_server";
1409 ASSERT_EQ(OK, rpcBinder->pingBinder());
1410}
1411
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001412class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1413public:
1414 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001415 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001416 std::to_string(std::get<1>(info.param));
1417 }
1418};
1419
1420TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1421 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1422 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001423 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001424 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001425 ASSERT_FALSE(server->hasServer());
1426 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1427 ASSERT_TRUE(server->hasServer());
1428 base::unique_fd retrieved = server->releaseServer();
1429 ASSERT_FALSE(server->hasServer());
1430 ASSERT_EQ(sinkFd, retrieved.get());
1431}
1432
1433TEST_P(BinderRpcServerOnly, Shutdown) {
1434 if constexpr (!kEnableRpcThreads) {
1435 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1436 }
1437
1438 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001439 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001440 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001441 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1442 auto joinEnds = std::make_shared<OneOffSignal>();
1443
1444 // If things are broken and the thread never stops, don't block other tests. Because the thread
1445 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1446 // shared pointers are passed.
1447 std::thread([server, joinEnds] {
1448 server->join();
1449 joinEnds->notify();
1450 }).detach();
1451
1452 bool shutdown = false;
1453 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001454 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001455 if (server->shutdown()) shutdown = true;
1456 }
1457 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1458
1459 ASSERT_TRUE(joinEnds->wait(2s))
1460 << "After server->shutdown() returns true, join() did not stop after 2s";
1461}
1462
Frederick Mayledc07cf82022-05-26 20:30:12 +00001463INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1464 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1465 ::testing::ValuesIn(testVersions())),
1466 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001467
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001468class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001469public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001470 // Only parameterized only server version because `RpcSession` is bypassed
1471 // in the client half of the tests.
1472 using Param =
1473 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001474 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001475
1476 // A server that handles client socket connections.
1477 class Server {
1478 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001479 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1480
Yifan Hong1deca4b2021-09-10 16:16:44 -07001481 explicit Server() {}
1482 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001483 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001484 [[nodiscard]] AssertionResult setUp(
1485 const Param& param,
1486 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001487 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001488 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001489 if (!rpcServer->setProtocolVersion(serverVersion)) {
1490 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1491 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001492 switch (socketType) {
1493 case SocketType::PRECONNECTED: {
1494 return AssertionFailure() << "Not supported by this test";
1495 } break;
1496 case SocketType::UNIX: {
1497 auto addr = allocateSocketAddress();
1498 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1499 if (status != OK) {
1500 return AssertionFailure()
1501 << "setupUnixDomainServer: " << statusToString(status);
1502 }
1503 mConnectToServer = [addr] {
1504 return connectTo(UnixSocketAddress(addr.c_str()));
1505 };
1506 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001507 case SocketType::UNIX_BOOTSTRAP: {
1508 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1509 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1510 return AssertionFailure() << "Socketpair() failed";
1511 }
1512 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1513 std::move(bootstrapFdServer));
1514 if (status != OK) {
1515 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1516 << statusToString(status);
1517 }
1518 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1519 mAcceptConnection = &Server::recvmsgServerConnection;
1520 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1521 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001522 case SocketType::UNIX_RAW: {
1523 auto addr = allocateSocketAddress();
1524 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1525 if (status != OK) {
1526 return AssertionFailure()
1527 << "setupRawSocketServer: " << statusToString(status);
1528 }
1529 mConnectToServer = [addr] {
1530 return connectTo(UnixSocketAddress(addr.c_str()));
1531 };
1532 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001533 case SocketType::VSOCK: {
1534 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001535 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001536 if (status != OK) {
1537 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1538 }
1539 mConnectToServer = [port] {
1540 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1541 };
1542 } break;
1543 case SocketType::INET: {
1544 unsigned int port;
1545 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1546 if (status != OK) {
1547 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1548 }
1549 mConnectToServer = [port] {
1550 const char* addr = kLocalInetAddress;
1551 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1552 if (aiStart == nullptr) return base::unique_fd{};
1553 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1554 auto fd = connectTo(
1555 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1556 if (fd.ok()) return fd;
1557 }
1558 ALOGE("None of the socket address resolved for %s:%u can be connected",
1559 addr, port);
1560 return base::unique_fd{};
1561 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001562 } break;
1563 case SocketType::TIPC: {
1564 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1565 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001566 }
1567 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001568 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001569 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001570 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1571 mSetup = true;
1572 return AssertionSuccess();
1573 }
1574 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1575 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1576 return mCertVerifier;
1577 }
1578 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1579 void start() {
1580 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1581 mThread = std::make_unique<std::thread>(&Server::run, this);
1582 }
David Brazdil21c887c2022-09-23 12:25:18 +01001583
1584 base::unique_fd acceptServerConnection() {
1585 return base::unique_fd(TEMP_FAILURE_RETRY(
1586 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1587 }
1588
1589 base::unique_fd recvmsgServerConnection() {
1590 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1591 int buf;
1592 iovec iov{&buf, sizeof(buf)};
1593
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001594 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
David Brazdil21c887c2022-09-23 12:25:18 +01001595 int savedErrno = errno;
1596 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1597 }
1598 if (fds.size() != 1) {
1599 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1600 }
1601 return std::move(std::get<base::unique_fd>(fds[0]));
1602 }
1603
Yifan Hong1deca4b2021-09-10 16:16:44 -07001604 void run() {
1605 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1606
1607 std::vector<std::thread> threads;
1608 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001609 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001610 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1611 }
1612
1613 for (auto& thread : threads) thread.join();
1614 }
1615 void handleOne(android::base::unique_fd acceptedFd) {
1616 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001617 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001618 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001620 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 }
Yifan Honge07d2732021-09-13 21:59:14 -07001622 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001623 shutdown();
1624 join();
1625 }
1626 void shutdown() { mFdTrigger->trigger(); }
1627
1628 void setPostConnect(
1629 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1630 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001631 }
1632
1633 private:
1634 std::unique_ptr<std::thread> mThread;
1635 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001636 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001638 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001639 std::unique_ptr<RpcTransportCtx> mCtx;
1640 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1641 std::make_shared<RpcCertificateVerifierSimple>();
1642 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001643 // The function invoked after connection and handshake. By default, it is
1644 // |defaultPostConnect| that sends |kMessage| to the client.
1645 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1646 Server::defaultPostConnect;
1647
1648 void join() {
1649 if (mThread != nullptr) {
1650 mThread->join();
1651 mThread = nullptr;
1652 }
1653 }
1654
1655 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1656 FdTrigger* fdTrigger) {
1657 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001658 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001659 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001660 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001661 if (status != OK) return AssertionFailure() << statusToString(status);
1662 return AssertionSuccess();
1663 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001664 };
1665
1666 class Client {
1667 public:
1668 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1669 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001670 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001671 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1672 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001673 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001674 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001675 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1676 return AssertionSuccess();
1677 }
1678 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1679 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1680 return mCertVerifier;
1681 }
Yifan Hong67519322021-09-13 18:51:16 -07001682 // connect() and do handshake
1683 bool setUpTransport() {
1684 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001685 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001686 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1687 return mClientTransport != nullptr;
1688 }
1689 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1690 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1691 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001692 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001693 status_t readStatus =
1694 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001695 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001696 if (readStatus != OK) {
1697 return AssertionFailure() << statusToString(readStatus);
1698 }
1699 if (readMessage != expectedMessage) {
1700 return AssertionFailure()
1701 << "Expected " << expectedMessage << ", actual " << readMessage;
1702 }
1703 return AssertionSuccess();
1704 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001705 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001706 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001707 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1708 return;
1709 }
1710 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001711 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001712 }
1713
Pawan49d74cb2022-08-03 21:19:11 +00001714 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1715
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 private:
1717 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001718 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1720 std::unique_ptr<RpcTransportCtx> mCtx;
1721 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1722 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001723 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724 };
1725
1726 // Make A trust B.
1727 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001728 static status_t trust(RpcSecurity rpcSecurity,
1729 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1730 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001731 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001732 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1733 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1734 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735 }
1736
1737 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001738};
1739
1740class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1741public:
1742 using Server = RpcTransportTestUtils::Server;
1743 using Client = RpcTransportTestUtils::Client;
1744 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001745 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001746 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001747 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001748 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001749 return ret;
1750 }
1751 static std::vector<ParamType> getRpcTranportTestParams() {
1752 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001753 for (auto serverVersion : testVersions()) {
1754 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1755 for (auto rpcSecurity : RpcSecurityValues()) {
1756 switch (rpcSecurity) {
1757 case RpcSecurity::RAW: {
1758 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1759 } break;
1760 case RpcSecurity::TLS: {
1761 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1762 serverVersion);
1763 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1764 serverVersion);
1765 } break;
1766 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001767 }
1768 }
1769 }
1770 return ret;
1771 }
1772 template <typename A, typename B>
1773 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001774 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1775 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001776 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1777 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001778 void SetUp() override {
1779 if constexpr (!kEnableRpcThreads) {
1780 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1781 }
1782 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783};
1784
1785TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001786 auto server = std::make_unique<Server>();
1787 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788
1789 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791
1792 ASSERT_EQ(OK, trust(&client, server));
1793 ASSERT_EQ(OK, trust(server, &client));
1794
1795 server->start();
1796 client.run();
1797}
1798
1799TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001800 auto server = std::make_unique<Server>();
1801 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001802
1803 std::vector<Client> clients;
1804 for (int i = 0; i < 2; i++) {
1805 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001806 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001807 ASSERT_EQ(OK, trust(&client, server));
1808 ASSERT_EQ(OK, trust(server, &client));
1809 }
1810
1811 server->start();
1812 for (auto& client : clients) client.run();
1813}
1814
1815TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001816 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1817 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001818
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001819 auto untrustedServer = std::make_unique<Server>();
1820 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001821
1822 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001823 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824
1825 ASSERT_EQ(OK, trust(untrustedServer, &client));
1826
1827 untrustedServer->start();
1828
1829 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1830 // the client can't verify the server's identity.
1831 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1832 client.run(handshakeOk);
1833}
1834TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001835 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1836 (void)serverVersion;
1837
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001838 auto validServer = std::make_unique<Server>();
1839 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001840
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001841 auto maliciousServer = std::make_unique<Server>();
1842 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001843
1844 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001845 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001846
1847 ASSERT_EQ(OK, trust(&client, validServer));
1848 ASSERT_EQ(OK, trust(validServer, &client));
1849 ASSERT_EQ(OK, trust(maliciousServer, &client));
1850
1851 maliciousServer->start();
1852
1853 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1854 // the client can't verify the server's identity.
1855 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1856 client.run(handshakeOk);
1857}
1858
1859TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001860 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1861 (void)serverVersion;
1862
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001863 auto server = std::make_unique<Server>();
1864 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001865
1866 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001868
1869 ASSERT_EQ(OK, trust(&client, server));
1870
1871 server->start();
1872
1873 // For TLS, Client should be able to verify server's identity, so client should see
1874 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1875 // identity and should drop the connection, so client shouldn't be able to read anything.
1876 bool readOk = rpcSecurity != RpcSecurity::TLS;
1877 client.run(true, readOk);
1878}
1879
1880TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001881 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1882 (void)serverVersion;
1883
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001884 auto server = std::make_unique<Server>();
1885 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001886
1887 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001888 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001889 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001890 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001891
1892 ASSERT_EQ(OK, trust(&validClient, server));
1893 ASSERT_EQ(OK, trust(&maliciousClient, server));
1894
1895 server->start();
1896
1897 // See UntrustedClient.
1898 bool readOk = rpcSecurity != RpcSecurity::TLS;
1899 maliciousClient.run(true, readOk);
1900}
1901
Yifan Hong67519322021-09-13 18:51:16 -07001902TEST_P(RpcTransportTest, Trigger) {
1903 std::string msg2 = ", world!";
1904 std::mutex writeMutex;
1905 std::condition_variable writeCv;
1906 bool shouldContinueWriting = false;
1907 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001908 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001909 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001910 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1911 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001912 if (status != OK) return AssertionFailure() << statusToString(status);
1913
1914 {
1915 std::unique_lock<std::mutex> lock(writeMutex);
1916 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1917 return AssertionFailure() << "write barrier not cleared in time!";
1918 }
1919 }
1920
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001921 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001922 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1923 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001924 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001925 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001926 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001927 << statusToString(status);
1928 return AssertionSuccess();
1929 };
1930
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931 auto server = std::make_unique<Server>();
1932 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001933
1934 // Set up client
1935 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001937
1938 // Exchange keys
1939 ASSERT_EQ(OK, trust(&client, server));
1940 ASSERT_EQ(OK, trust(server, &client));
1941
1942 server->setPostConnect(serverPostConnect);
1943
Yifan Hong67519322021-09-13 18:51:16 -07001944 server->start();
1945 // connect() to server and do handshake
1946 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001947 // read the first message. This ensures that server has finished handshake and start handling
1948 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001949 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001950 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1951 // write is on an FdTrigger that has been shut down.
1952 server->shutdown();
1953 // Continues server thread to write the second message.
1954 {
Yifan Hong22211f82021-09-14 12:32:25 -07001955 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001956 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001957 }
Yifan Hong22211f82021-09-14 12:32:25 -07001958 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001959 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001960 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001961 // On the client side, second read fails with DEAD_OBJECT
1962 ASSERT_FALSE(client.readMessage(msg2));
1963}
1964
Pawan49d74cb2022-08-03 21:19:11 +00001965TEST_P(RpcTransportTest, CheckWaitingForRead) {
1966 std::mutex readMutex;
1967 std::condition_variable readCv;
1968 bool shouldContinueReading = false;
1969 // Server will write data on transport once its started
1970 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1971 std::string message(RpcTransportTestUtils::kMessage);
1972 iovec messageIov{message.data(), message.size()};
1973 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1974 std::nullopt, nullptr);
1975 if (status != OK) return AssertionFailure() << statusToString(status);
1976
1977 {
1978 std::unique_lock<std::mutex> lock(readMutex);
1979 shouldContinueReading = true;
1980 lock.unlock();
1981 readCv.notify_all();
1982 }
1983 return AssertionSuccess();
1984 };
1985
1986 // Setup Server and client
1987 auto server = std::make_unique<Server>();
1988 ASSERT_TRUE(server->setUp(GetParam()));
1989
1990 Client client(server->getConnectToServerFn());
1991 ASSERT_TRUE(client.setUp(GetParam()));
1992
1993 ASSERT_EQ(OK, trust(&client, server));
1994 ASSERT_EQ(OK, trust(server, &client));
1995 server->setPostConnect(serverPostConnect);
1996
1997 server->start();
1998 ASSERT_TRUE(client.setUpTransport());
1999 {
2000 // Wait till server writes data
2001 std::unique_lock<std::mutex> lock(readMutex);
2002 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2003 }
2004
2005 // Since there is no read polling here, we will get polling count 0
2006 ASSERT_FALSE(client.isTransportWaiting());
2007 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2008 // Thread should increment polling count, read and decrement polling count
2009 // Again, polling count should be zero here
2010 ASSERT_FALSE(client.isTransportWaiting());
2011
2012 server->shutdown();
2013}
2014
Yifan Hong1deca4b2021-09-10 16:16:44 -07002015INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002016 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002017 RpcTransportTest::PrintParamInfo);
2018
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002019class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002020 : public testing::TestWithParam<
2021 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002022public:
2023 template <typename A, typename B>
2024 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002025 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2026 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002027 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2028 }
2029 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002030 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2031 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2032 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002033 };
2034};
2035
2036TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002037 if constexpr (!kEnableRpcThreads) {
2038 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2039 }
2040
Frederick Mayledc07cf82022-05-26 20:30:12 +00002041 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002042
2043 std::vector<uint8_t> pkeyData, certData;
2044 {
2045 auto pkey = makeKeyPairForSelfSignedCert();
2046 ASSERT_NE(nullptr, pkey);
2047 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2048 ASSERT_NE(nullptr, cert);
2049 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2050 certData = serializeCertificate(cert.get(), certificateFormat);
2051 }
2052
2053 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2054 auto desCert = deserializeCertificate(certData, certificateFormat);
2055 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002056 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2057 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002058
2059 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2060 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2061
2062 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2063 ASSERT_TRUE(client.setUp(utilsParam));
2064
2065 ASSERT_EQ(OK, trust(&client, server));
2066 ASSERT_EQ(OK, trust(server, &client));
2067
2068 server->start();
2069 client.run();
2070}
2071
2072INSTANTIATE_TEST_CASE_P(
2073 BinderRpc, RpcTransportTlsKeyTest,
2074 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2075 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002076 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2077 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002078 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002079#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002080
Steven Morelandc1635952021-04-01 16:20:47 +00002081} // namespace android
2082
2083int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002084 ::testing::InitGoogleTest(&argc, argv);
2085 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002086
Steven Moreland5553ac42020-11-11 02:14:45 +00002087 return RUN_ALL_TESTS();
2088}