blob: 1340ea1d2c339566fea690b92a3e5ba405b3666f [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
Frederick Maylea12b0962022-06-25 01:13:22 +000021#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022
Steven Morelandc1635952021-04-01 16:20:47 +000023#include <chrono>
24#include <cstdlib>
25#include <iostream>
26#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000027#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000028
Andrei Homescu2a298012022-06-15 01:08:54 +000029#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070030#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000031#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000032#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000033
Andrei Homescud65666d2023-03-03 07:28:02 +000034#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000035#include <binder/RpcTransportTipcAndroid.h>
36#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000037#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000038
Andrei Homescu2a298012022-06-15 01:08:54 +000039#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000040#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000041
Yifan Hong1a235852021-05-13 16:07:47 -070042using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070043using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070044using testing::AssertionFailure;
45using testing::AssertionResult;
46using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070047
Steven Moreland5553ac42020-11-11 02:14:45 +000048namespace android {
49
Andrei Homescu12106de2022-04-27 04:42:21 +000050#ifdef BINDER_TEST_NO_SHARED_LIBS
51constexpr bool kEnableSharedLibs = false;
52#else
53constexpr bool kEnableSharedLibs = true;
54#endif
55
Andrei Homescud65666d2023-03-03 07:28:02 +000056#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000057constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
58#endif
59
Frederick Maylea12b0962022-06-25 01:13:22 +000060static std::string WaitStatusToString(int wstatus) {
61 if (WIFEXITED(wstatus)) {
62 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
63 }
64 if (WIFSIGNALED(wstatus)) {
65 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
66 }
67 return base::StringPrintf("unexpected state %d", wstatus);
68}
69
Steven Moreland276d8df2022-09-28 23:56:39 +000070static void debugBacktrace(pid_t pid) {
71 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
72 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
73}
74
Steven Moreland5553ac42020-11-11 02:14:45 +000075class Process {
76public:
Andrei Homescu96834632022-10-14 00:49:49 +000077 Process(Process&& other)
78 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
79 mReadEnd(std::move(other.mReadEnd)),
80 mWriteEnd(std::move(other.mWriteEnd)) {
81 // The default move constructor doesn't clear mPid after moving it,
82 // which we need to do because the destructor checks for mPid!=0
83 mPid = other.mPid;
84 other.mPid = 0;
85 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070086 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
87 android::base::borrowed_fd /* readEnd */)>& f) {
88 android::base::unique_fd childWriteEnd;
89 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000090 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
91 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000092 if (0 == (mPid = fork())) {
93 // racey: assume parent doesn't crash before this is set
94 prctl(PR_SET_PDEATHSIG, SIGHUP);
95
Yifan Hong1deca4b2021-09-10 16:16:44 -070096 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000097
98 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000099 }
100 }
101 ~Process() {
102 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000103 int wstatus;
104 waitpid(mPid, &wstatus, 0);
105 if (mCustomExitStatusCheck) {
106 mCustomExitStatusCheck(wstatus);
107 } else {
108 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
109 << "server process failed: " << WaitStatusToString(wstatus);
110 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000111 }
112 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700113 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700114 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000115
Frederick Maylea12b0962022-06-25 01:13:22 +0000116 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
117 mCustomExitStatusCheck = std::move(f);
118 }
119
Frederick Mayle69a0c992022-05-26 20:38:39 +0000120 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
121 void terminate() { kill(mPid, SIGTERM); }
122
Steven Moreland276d8df2022-09-28 23:56:39 +0000123 pid_t getPid() { return mPid; }
124
Steven Moreland5553ac42020-11-11 02:14:45 +0000125private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000126 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700128 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700129 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000130};
131
132static std::string allocateSocketAddress() {
133 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000134 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000135 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700136 unlink(ret.c_str());
137 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000138};
139
Steven Morelandda573042021-06-12 01:13:45 +0000140static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000141 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000142 return vsockPort++;
143}
144
Alice Wang893a9912022-10-24 10:44:09 +0000145static base::unique_fd initUnixSocket(std::string addr) {
146 auto socket_addr = UnixSocketAddress(addr.c_str());
147 base::unique_fd fd(
148 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
149 CHECK(fd.ok());
150 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
151 return fd;
152}
153
Andrei Homescu96834632022-10-14 00:49:49 +0000154// Destructors need to be defined, even if pure virtual
155ProcessSession::~ProcessSession() {}
156
157class LinuxProcessSession : public ProcessSession {
158public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000159 // reference to process hosting a socket server
160 Process host;
161
Andrei Homescu96834632022-10-14 00:49:49 +0000162 LinuxProcessSession(LinuxProcessSession&&) = default;
163 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
164 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165 for (auto& session : sessions) {
166 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000167 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000168
Steven Moreland67f85902023-03-15 01:13:49 +0000169 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
170 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 EXPECT_NE(nullptr, session);
174 EXPECT_NE(nullptr, session->state());
175 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000176
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 wp<RpcSession> weakSession = session;
178 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000179
Steven Moreland57042712022-10-04 23:56:45 +0000180 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
181 // the object should not actually be promotable. By looping, we distinguish a race here
182 // from a bug causing the object to not be promotable.
183 for (size_t i = 0; i < 3; i++) {
184 sp<RpcSession> strongSession = weakSession.promote();
185 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000186 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000187 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
188 "Leaked sess: ")
189 << strongSession->getStrongCount() << " checked time " << i;
190
191 if (strongSession != nullptr) {
192 sleep(1);
193 }
194 }
Steven Moreland736664b2021-05-01 04:27:25 +0000195 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000197
Andrei Homescu96834632022-10-14 00:49:49 +0000198 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
199 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000200 }
Andrei Homescu96834632022-10-14 00:49:49 +0000201
202 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000203};
204
Yifan Hong1deca4b2021-09-10 16:16:44 -0700205static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700206 base::unique_fd serverFd(
207 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
208 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700209 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
210 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700211
212 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
213 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700214 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
215 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700216 }
217 return serverFd;
218}
219
Andrei Homescud65666d2023-03-03 07:28:02 +0000220#ifndef BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100221static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
222 base::unique_fd sockClient, sockServer;
223 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
224 int savedErrno = errno;
225 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
226 }
227
228 int zero = 0;
229 iovec iov{&zero, sizeof(zero)};
230 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
231 fds.emplace_back(std::move(sockServer));
232
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000233 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
David Brazdil21c887c2022-09-23 12:25:18 +0100234 int savedErrno = errno;
235 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
236 }
237 return std::move(sockClient);
238}
Andrei Homescud65666d2023-03-03 07:28:02 +0000239#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100240
Andrei Homescuf30148c2023-03-10 00:31:45 +0000241std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
242 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000243}
Andrei Homescu2a298012022-06-15 01:08:54 +0000244
Andrei Homescu96834632022-10-14 00:49:49 +0000245// This creates a new process serving an interface on a certain number of
246// threads.
247std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
248 const BinderRpcOptions& options) {
249 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000250
Steven Moreland67f85902023-03-15 01:13:49 +0000251 if (options.numIncomingConnectionsBySession.size() != 0) {
252 CHECK_EQ(options.numIncomingConnectionsBySession.size(), options.numSessions);
253 }
254
Steven Morelandb469f432023-07-28 22:13:47 +0000255 SocketType socketType = GetParam().type;
256 RpcSecurity rpcSecurity = GetParam().security;
257 uint32_t clientVersion = GetParam().clientVersion;
258 uint32_t serverVersion = GetParam().serverVersion;
259 bool singleThreaded = GetParam().singleThreaded;
260 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000261
262 std::string path = android::base::GetExecutableDirectory();
263 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
264 singleThreaded ? "_single_threaded" : "",
265 noKernel ? "_no_kernel" : "");
266
Alice Wang1ef010b2022-11-14 09:09:25 +0000267 base::unique_fd bootstrapClientFd, socketFd;
268
Alice Wang893a9912022-10-24 10:44:09 +0000269 auto addr = allocateSocketAddress();
270 // Initializes the socket before the fork/exec.
271 if (socketType == SocketType::UNIX_RAW) {
272 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000273 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
274 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
275 // This is because we cannot pass ParcelFileDescriptor over a pipe.
276 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
277 int savedErrno = errno;
278 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
279 }
Alice Wang893a9912022-10-24 10:44:09 +0000280 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000281
Andrei Homescu96834632022-10-14 00:49:49 +0000282 auto ret = std::make_unique<LinuxProcessSession>(
283 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000284 if (socketType == SocketType::TIPC) {
285 // Trusty has a single persistent service
286 return;
287 }
288
Andrei Homescu96834632022-10-14 00:49:49 +0000289 auto writeFd = std::to_string(writeEnd.get());
290 auto readFd = std::to_string(readEnd.get());
291 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
292 NULL);
293 }));
294
295 BinderRpcTestServerConfig serverConfig;
296 serverConfig.numThreads = options.numThreads;
297 serverConfig.socketType = static_cast<int32_t>(socketType);
298 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
299 serverConfig.serverVersion = serverVersion;
300 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000301 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000302 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000303 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
304 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
305 static_cast<int32_t>(mode));
306 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000307 if (socketType != SocketType::TIPC) {
308 writeToFd(ret->host.writeEnd(), serverConfig);
309 }
Andrei Homescu96834632022-10-14 00:49:49 +0000310
311 std::vector<sp<RpcSession>> sessions;
312 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
313 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000314 std::unique_ptr<RpcTransportCtxFactory> factory;
315 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000316#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000317 factory = RpcTransportCtxFactoryTipcAndroid::make();
318#else
319 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
320#endif
321 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000322 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000323 }
324 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100325 }
326
Andrei Homescu68a55612022-08-02 01:25:15 +0000327 BinderRpcTestServerInfo serverInfo;
328 if (socketType != SocketType::TIPC) {
329 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
330 BinderRpcTestClientInfo clientInfo;
331 for (const auto& session : sessions) {
332 auto& parcelableCert = clientInfo.certs.emplace_back();
333 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
334 }
335 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000336
Andrei Homescu68a55612022-08-02 01:25:15 +0000337 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
338 if (socketType == SocketType::INET) {
339 CHECK_NE(0, serverInfo.port);
340 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000341
Andrei Homescu68a55612022-08-02 01:25:15 +0000342 if (rpcSecurity == RpcSecurity::TLS) {
343 const auto& serverCert = serverInfo.cert.data;
344 CHECK_EQ(OK,
345 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
346 serverCert));
347 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700348 }
349
Andrei Homescu96834632022-10-14 00:49:49 +0000350 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000351
Steven Moreland67f85902023-03-15 01:13:49 +0000352 for (size_t i = 0; i < sessions.size(); i++) {
353 const auto& session = sessions.at(i);
354
355 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
356 ? options.numIncomingConnectionsBySession.at(i)
357 : 0;
358
Andrei Homescu96834632022-10-14 00:49:49 +0000359 CHECK(session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000360 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000361 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000362 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000363
Andrei Homescu96834632022-10-14 00:49:49 +0000364 switch (socketType) {
365 case SocketType::PRECONNECTED:
366 status = session->setupPreconnectedClient({}, [=]() {
367 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
368 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000369 break;
Alice Wang893a9912022-10-24 10:44:09 +0000370 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000371 case SocketType::UNIX:
372 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
373 break;
374 case SocketType::UNIX_BOOTSTRAP:
375 status = session->setupUnixDomainSocketBootstrapClient(
376 base::unique_fd(dup(bootstrapClientFd.get())));
377 break;
378 case SocketType::VSOCK:
379 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
380 break;
381 case SocketType::INET:
382 status = session->setupInetClient("127.0.0.1", serverInfo.port);
383 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000384 case SocketType::TIPC:
385 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000386#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000387 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000388 for (size_t i = 0; i < 5; i++) {
389 // Try to connect several times,
390 // in case the service is slow to start
391 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
392 if (tipcFd >= 0) {
393 return android::base::unique_fd(tipcFd);
394 }
395 usleep(50000);
396 }
397 return android::base::unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000398#else
399 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
400 return android::base::unique_fd();
401#endif
402 });
403 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000404 default:
405 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000406 }
Andrei Homescu96834632022-10-14 00:49:49 +0000407 if (options.allowConnectFailure && status != OK) {
408 ret->sessions.clear();
409 break;
410 }
411 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
412 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000413 }
Andrei Homescu96834632022-10-14 00:49:49 +0000414 return ret;
415}
Steven Morelandc1635952021-04-01 16:20:47 +0000416
Andrei Homescua858b0e2022-08-01 23:43:09 +0000417TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
418 if (clientOrServerSingleThreaded()) {
419 GTEST_SKIP() << "This test requires multiple threads";
420 }
421
Steven Moreland5553ac42020-11-11 02:14:45 +0000422 constexpr size_t kNumThreads = 10;
423
Steven Moreland4313d7e2021-07-15 23:41:22 +0000424 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000425
426 EXPECT_OK(proc.rootIface->lock());
427
428 // block all but one thread taking locks
429 std::vector<std::thread> ts;
430 for (size_t i = 0; i < kNumThreads - 1; i++) {
431 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
432 }
433
Steven Morelandd6d816f2022-12-23 01:37:17 +0000434 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000435
436 // other calls still work
437 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
438
Steven Morelandd6d816f2022-12-23 01:37:17 +0000439 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000440 size_t epochMsBefore = epochMillis();
441 // after this, we should never see a response within this time
442 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
443
444 // this call should be blocked for blockTimeMs
445 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
446
447 size_t epochMsAfter = epochMillis();
448 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
449
450 for (auto& t : ts) t.join();
451}
452
Steven Moreland27f620a2023-03-06 19:44:36 +0000453static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000454 size_t epochMsBefore = epochMillis();
455
456 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700457 for (size_t i = 0; i < numCalls; i++) {
458 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000459 }
460
461 for (auto& t : ts) t.join();
462
463 size_t epochMsAfter = epochMillis();
464
Yifan Hong1f44f982021-10-08 17:16:47 -0700465 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000466
Steven Moreland9c203222023-05-31 21:26:41 +0000467 // Potential flake, but make sure calls are handled in parallel. Due
468 // to past flakes, this only checks that the amount of time taken has
469 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
470 // check this more exactly.
471 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700472}
473
Andrei Homescua858b0e2022-08-01 23:43:09 +0000474TEST_P(BinderRpc, ThreadPoolOverSaturated) {
475 if (clientOrServerSingleThreaded()) {
476 GTEST_SKIP() << "This test requires multiple threads";
477 }
478
Yifan Hong1f44f982021-10-08 17:16:47 -0700479 constexpr size_t kNumThreads = 10;
480 constexpr size_t kNumCalls = kNumThreads + 3;
481 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000482
483 // b/272429574 - below 500ms, the test fails
484 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700485}
486
Andrei Homescua858b0e2022-08-01 23:43:09 +0000487TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
488 if (clientOrServerSingleThreaded()) {
489 GTEST_SKIP() << "This test requires multiple threads";
490 }
491
Yifan Hong1f44f982021-10-08 17:16:47 -0700492 constexpr size_t kNumThreads = 20;
493 constexpr size_t kNumOutgoingConnections = 10;
494 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
495 auto proc = createRpcTestSocketServerProcess(
496 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000497
498 // b/272429574 - below 500ms, the test fails
499 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000500}
501
Andrei Homescua858b0e2022-08-01 23:43:09 +0000502TEST_P(BinderRpc, ThreadingStressTest) {
503 if (clientOrServerSingleThreaded()) {
504 GTEST_SKIP() << "This test requires multiple threads";
505 }
506
Steven Moreland27f620a2023-03-06 19:44:36 +0000507 constexpr size_t kNumClientThreads = 5;
508 constexpr size_t kNumServerThreads = 5;
509 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000510
Steven Moreland4313d7e2021-07-15 23:41:22 +0000511 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000512
513 std::vector<std::thread> threads;
514 for (size_t i = 0; i < kNumClientThreads; i++) {
515 threads.push_back(std::thread([&] {
516 for (size_t j = 0; j < kNumCalls; j++) {
517 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000518 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 EXPECT_EQ(proc.rootBinder, out);
520 }
521 }));
522 }
523
524 for (auto& t : threads) t.join();
525}
526
Steven Moreland925ba0a2021-09-17 18:06:32 -0700527static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
528 std::vector<std::thread> threads;
529 for (size_t i = 0; i < threadCount; i++) {
530 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
531 }
532 for (auto& t : threads) t.join();
533}
534
Andrei Homescua858b0e2022-08-01 23:43:09 +0000535TEST_P(BinderRpc, OnewayStressTest) {
536 if (clientOrServerSingleThreaded()) {
537 GTEST_SKIP() << "This test requires multiple threads";
538 }
539
Steven Morelandc6046982021-04-20 00:49:42 +0000540 constexpr size_t kNumClientThreads = 10;
541 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700542 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000543
Steven Moreland4313d7e2021-07-15 23:41:22 +0000544 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000545
546 std::vector<std::thread> threads;
547 for (size_t i = 0; i < kNumClientThreads; i++) {
548 threads.push_back(std::thread([&] {
549 for (size_t j = 0; j < kNumCalls; j++) {
550 EXPECT_OK(proc.rootIface->sendString("a"));
551 }
Steven Morelandc6046982021-04-20 00:49:42 +0000552 }));
553 }
554
555 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700556
557 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000558}
559
Frederick Mayleb0221d12022-10-03 23:10:53 +0000560TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
561 if (!supportsFdTransport()) {
562 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
563 }
564 if (clientOrServerSingleThreaded()) {
565 GTEST_SKIP() << "This test requires multiple threads";
566 }
567
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000568 constexpr size_t kNumServerThreads = 3;
569
Frederick Mayleb0221d12022-10-03 23:10:53 +0000570 // This test forces a oneway transaction to be queued by issuing two
571 // `blockingSendFdOneway` calls, then drains the queue by issuing two
572 // `blockingRecvFd` calls.
573 //
574 // For more details about the queuing semantics see
575 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
576
577 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000578 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000579 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
580 .serverSupportedFileDescriptorTransportModes =
581 {RpcSession::FileDescriptorTransportMode::UNIX},
582 });
583
584 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
585 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
586 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
587 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
588
589 android::os::ParcelFileDescriptor fdA;
590 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
591 std::string result;
592 CHECK(android::base::ReadFdToString(fdA.get(), &result));
593 EXPECT_EQ(result, "a");
594
595 android::os::ParcelFileDescriptor fdB;
596 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
597 CHECK(android::base::ReadFdToString(fdB.get(), &result));
598 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000599
600 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000601}
602
Andrei Homescua858b0e2022-08-01 23:43:09 +0000603TEST_P(BinderRpc, OnewayCallQueueing) {
604 if (clientOrServerSingleThreaded()) {
605 GTEST_SKIP() << "This test requires multiple threads";
606 }
607
Frederick Mayle96872592023-03-07 14:56:15 -0800608 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000610
611 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000612 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000613
Frederick Mayle96872592023-03-07 14:56:15 -0800614 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700615 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800616 for (size_t i = 0; i + 1 < kNumQueued; i++) {
617 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000618 }
Frederick Mayle96872592023-03-07 14:56:15 -0800619 for (size_t i = 0; i + 1 < kNumQueued; i++) {
620 int n;
621 proc.rootIface->blockingRecvInt(&n);
622 EXPECT_EQ(n, i);
623 }
Steven Morelandf5174272021-05-25 00:39:28 +0000624
Steven Moreland925ba0a2021-09-17 18:06:32 -0700625 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000626}
627
Andrei Homescua858b0e2022-08-01 23:43:09 +0000628TEST_P(BinderRpc, OnewayCallExhaustion) {
629 if (clientOrServerSingleThreaded()) {
630 GTEST_SKIP() << "This test requires multiple threads";
631 }
632
Steven Morelandd45be622021-06-04 02:19:37 +0000633 constexpr size_t kNumClients = 2;
634 constexpr size_t kTooLongMs = 1000;
635
Steven Moreland4313d7e2021-07-15 23:41:22 +0000636 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000637
638 // Build up oneway calls on the second session to make sure it terminates
639 // and shuts down. The first session should be unaffected (proc destructor
640 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000641 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000642
643 std::vector<std::thread> threads;
644 for (size_t i = 0; i < kNumClients; i++) {
645 // one of these threads will get stuck queueing a transaction once the
646 // socket fills up, the other will be able to fill up transactions on
647 // this object
648 threads.push_back(std::thread([&] {
649 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
650 }
651 }));
652 }
653 for (auto& t : threads) t.join();
654
655 Status status = iface->sleepMsAsync(kTooLongMs);
656 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
657
Steven Moreland798e0d12021-07-14 23:19:25 +0000658 // now that it has died, wait for the remote session to shutdown
659 std::vector<int32_t> remoteCounts;
660 do {
661 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
662 } while (remoteCounts.size() == kNumClients);
663
Steven Morelandd45be622021-06-04 02:19:37 +0000664 // the second session should be shutdown in the other process by the time we
665 // are able to join above (it'll only be hung up once it finishes processing
666 // any pending commands). We need to erase this session from the record
667 // here, so that the destructor for our session won't check that this
668 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000669 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000670}
671
Steven Moreland67f85902023-03-15 01:13:49 +0000672TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
673 if (clientOrServerSingleThreaded()) {
674 GTEST_SKIP() << "This test requires multiple threads";
675 }
676
677 // session 0 - will check for leaks in destrutor of proc
678 // session 1 - we want to make sure it gets deleted when we drop all references to it
679 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700680 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000681
682 wp<RpcSession> session = proc.proc->sessions.at(1).session;
683
684 // remove all references to the second session
685 proc.proc->sessions.at(1).root = nullptr;
686 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
687
688 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
689 // to drain commands.
690 for (size_t i = 0; i < 100; i++) {
691 usleep(10 * 1000);
692 if (session.promote() == nullptr) break;
693 }
694
695 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000696
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000697 // now that it has died, wait for the remote session to shutdown
698 std::vector<int32_t> remoteCounts;
699 do {
700 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
701 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000702}
703
Devin Moore66d5b7a2022-07-07 21:42:10 +0000704TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000705 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000706 GTEST_SKIP() << "This test requires multiple threads";
707 }
708 class MyDeathRec : public IBinder::DeathRecipient {
709 public:
710 void binderDied(const wp<IBinder>& /* who */) override {
711 dead = true;
712 mCv.notify_one();
713 }
714 std::mutex mMtx;
715 std::condition_variable mCv;
716 bool dead = false;
717 };
718
719 // Death recipient needs to have an incoming connection to be called
720 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000721 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000722
723 auto dr = sp<MyDeathRec>::make();
724 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
725
726 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
727 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
728 }
729
730 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000731 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000732
733 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000734 // can't do this before checking the death recipient by calling
735 // forceShutdown earlier, because shutdownAndWait will also trigger
736 // a death recipient, but if we had a way to wait for the service
737 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000738 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000739 proc.expectAlreadyShutdown = true;
740}
741
742TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000743 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000744 GTEST_SKIP() << "This test requires multiple threads";
745 }
746 class MyDeathRec : public IBinder::DeathRecipient {
747 public:
748 void binderDied(const wp<IBinder>& /* who */) override {
749 dead = true;
750 mCv.notify_one();
751 }
752 std::mutex mMtx;
753 std::condition_variable mCv;
754 bool dead = false;
755 };
756
757 // Death recipient needs to have an incoming connection to be called
758 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000759 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000760
761 auto dr = sp<MyDeathRec>::make();
762 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
763
764 // Explicitly calling shutDownAndWait will cause the death recipients
765 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000766 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000767
768 std::unique_lock<std::mutex> lock(dr->mMtx);
769 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000770 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000771 }
772 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
773
Andrei Homescu96834632022-10-14 00:49:49 +0000774 proc.proc->terminate();
775 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000776 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
777 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
778 });
779 proc.expectAlreadyShutdown = true;
780}
781
Steven Moreland5ec743f2023-01-18 01:02:06 +0000782TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000783 if (socketType() == SocketType::TIPC) {
784 // This should work, but Trusty takes too long to restart the service
785 GTEST_SKIP() << "Service death test not supported on Trusty";
786 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000787 class MyDeathRec : public IBinder::DeathRecipient {
788 public:
789 void binderDied(const wp<IBinder>& /* who */) override {}
790 };
791
Steven Moreland67f85902023-03-15 01:13:49 +0000792 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000793
794 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000795 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000796}
797
798TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000799 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000800 GTEST_SKIP() << "This test requires multiple threads";
801 }
802 class MyDeathRec : public IBinder::DeathRecipient {
803 public:
804 void binderDied(const wp<IBinder>& /* who */) override {
805 GTEST_FAIL() << "This should not be called after unlinkToDeath";
806 }
807 };
808
809 // Death recipient needs to have an incoming connection to be called
810 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000811 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000812
813 auto dr = sp<MyDeathRec>::make();
814 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
815 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
816
Steven Moreland67f85902023-03-15 01:13:49 +0000817 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000818}
819
Steven Morelandc1635952021-04-01 16:20:47 +0000820TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000821 if (socketType() == SocketType::TIPC) {
822 // This should work, but Trusty takes too long to restart the service
823 GTEST_SKIP() << "Service death test not supported on Trusty";
824 }
825
Steven Moreland5553ac42020-11-11 02:14:45 +0000826 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000827 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000828
829 // make sure there is some state during crash
830 // 1. we hold their binder
831 sp<IBinderRpcSession> session;
832 EXPECT_OK(proc.rootIface->openSession("happy", &session));
833 // 2. they hold our binder
834 sp<IBinder> binder = new BBinder();
835 EXPECT_OK(proc.rootIface->holdBinder(binder));
836
837 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
838 << "Do death cleanup: " << doDeathCleanup;
839
Andrei Homescu96834632022-10-14 00:49:49 +0000840 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000841 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
842 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
843 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000844 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 }
846}
847
Steven Morelandd7302072021-05-15 01:32:04 +0000848TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000849 // This test only works if the current process shared the internal state of
850 // ProcessState with the service across the call to fork(). Both the static
851 // libraries and libbinder.so have their own separate copies of all the
852 // globals, so the test only works when the test client and service both use
853 // libbinder.so (when using static libraries, even a client and service
854 // using the same kind of static library should have separate copies of the
855 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000856 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000857 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
858 "at build time.";
859 }
860
Steven Moreland4313d7e2021-07-15 23:41:22 +0000861 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000862
Andrei Homescu2a298012022-06-15 01:08:54 +0000863 // we can't allocate IPCThreadState so actually the first time should
864 // succeed :(
865 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000866
867 // second time! we catch the error :)
868 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
869
Andrei Homescu96834632022-10-14 00:49:49 +0000870 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000871 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
872 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
873 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000874 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000875}
876
Frederick Mayle69a0c992022-05-26 20:38:39 +0000877TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000878 if (socketType() == SocketType::TIPC) {
879 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
880 }
881
Frederick Mayle69a0c992022-05-26 20:38:39 +0000882 auto proc = createRpcTestSocketServerProcess({
883 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
884 .serverSupportedFileDescriptorTransportModes =
885 {RpcSession::FileDescriptorTransportMode::UNIX},
886 .allowConnectFailure = true,
887 });
Andrei Homescu96834632022-10-14 00:49:49 +0000888 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
889 proc.proc->terminate();
890 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000891 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
892 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
893 });
894 proc.expectAlreadyShutdown = true;
895}
896
897TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000898 if (socketType() == SocketType::TIPC) {
899 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
900 }
901
Frederick Mayle69a0c992022-05-26 20:38:39 +0000902 auto proc = createRpcTestSocketServerProcess({
903 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
904 .serverSupportedFileDescriptorTransportModes =
905 {RpcSession::FileDescriptorTransportMode::NONE},
906 .allowConnectFailure = true,
907 });
Andrei Homescu96834632022-10-14 00:49:49 +0000908 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
909 proc.proc->terminate();
910 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000911 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
912 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
913 });
914 proc.expectAlreadyShutdown = true;
915}
916
917TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000918 if (socketType() == SocketType::TIPC) {
919 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
920 }
921
Frederick Mayle69a0c992022-05-26 20:38:39 +0000922 auto proc = createRpcTestSocketServerProcess({
923 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
924 .serverSupportedFileDescriptorTransportModes =
925 {RpcSession::FileDescriptorTransportMode::NONE,
926 RpcSession::FileDescriptorTransportMode::UNIX},
927 });
928
929 android::os::ParcelFileDescriptor out;
930 auto status = proc.rootIface->echoAsFile("hello", &out);
931 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
932}
933
934TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000935 if (socketType() == SocketType::TIPC) {
936 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
937 }
938
Frederick Mayle69a0c992022-05-26 20:38:39 +0000939 auto proc = createRpcTestSocketServerProcess({
940 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
941 .serverSupportedFileDescriptorTransportModes =
942 {RpcSession::FileDescriptorTransportMode::UNIX},
943 });
944
945 android::os::ParcelFileDescriptor out;
946 auto status = proc.rootIface->echoAsFile("hello", &out);
947 if (!supportsFdTransport()) {
948 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
949 return;
950 }
951 ASSERT_TRUE(status.isOk()) << status;
952
953 std::string result;
954 CHECK(android::base::ReadFdToString(out.get(), &result));
955 EXPECT_EQ(result, "hello");
956}
957
958TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000959 if (socketType() == SocketType::TIPC) {
960 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
961 }
962
Frederick Mayle69a0c992022-05-26 20:38:39 +0000963 auto proc = createRpcTestSocketServerProcess({
964 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
965 .serverSupportedFileDescriptorTransportModes =
966 {RpcSession::FileDescriptorTransportMode::UNIX},
967 });
968
969 std::vector<android::os::ParcelFileDescriptor> files;
970 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
971 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
972 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
973 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
974
975 android::os::ParcelFileDescriptor out;
976 auto status = proc.rootIface->concatFiles(files, &out);
977 if (!supportsFdTransport()) {
978 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
979 return;
980 }
981 ASSERT_TRUE(status.isOk()) << status;
982
983 std::string result;
984 CHECK(android::base::ReadFdToString(out.get(), &result));
985 EXPECT_EQ(result, "123abcd");
986}
987
988TEST_P(BinderRpc, SendMaxFiles) {
989 if (!supportsFdTransport()) {
990 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
991 }
992
993 auto proc = createRpcTestSocketServerProcess({
994 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
995 .serverSupportedFileDescriptorTransportModes =
996 {RpcSession::FileDescriptorTransportMode::UNIX},
997 });
998
999 std::vector<android::os::ParcelFileDescriptor> files;
1000 for (int i = 0; i < 253; i++) {
1001 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1002 }
1003
1004 android::os::ParcelFileDescriptor out;
1005 auto status = proc.rootIface->concatFiles(files, &out);
1006 ASSERT_TRUE(status.isOk()) << status;
1007
1008 std::string result;
1009 CHECK(android::base::ReadFdToString(out.get(), &result));
1010 EXPECT_EQ(result, std::string(253, 'a'));
1011}
1012
1013TEST_P(BinderRpc, SendTooManyFiles) {
1014 if (!supportsFdTransport()) {
1015 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1016 }
1017
1018 auto proc = createRpcTestSocketServerProcess({
1019 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1020 .serverSupportedFileDescriptorTransportModes =
1021 {RpcSession::FileDescriptorTransportMode::UNIX},
1022 });
1023
1024 std::vector<android::os::ParcelFileDescriptor> files;
1025 for (int i = 0; i < 254; i++) {
1026 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1027 }
1028
1029 android::os::ParcelFileDescriptor out;
1030 auto status = proc.rootIface->concatFiles(files, &out);
1031 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1032}
1033
Andrei Homescufc221502022-10-08 03:51:17 +00001034TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001035 if (socketType() == SocketType::TIPC) {
1036 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1037 }
1038
Andrei Homescufc221502022-10-08 03:51:17 +00001039 auto proc = createRpcTestSocketServerProcess({
1040 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1041 .serverSupportedFileDescriptorTransportModes =
1042 {RpcSession::FileDescriptorTransportMode::UNIX},
1043 });
1044
1045 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1046 ASSERT_NE(badFd, -1);
1047
1048 // Close the file descriptor so it becomes invalid for dup
1049 close(badFd);
1050
1051 Parcel p1;
1052 p1.markForBinder(proc.rootBinder);
1053 p1.writeInt32(3);
1054 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1055
1056 Parcel pRaw;
1057 pRaw.markForBinder(proc.rootBinder);
1058 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1059
1060 pRaw.setDataPosition(0);
1061 EXPECT_EQ(3, pRaw.readInt32());
1062 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1063}
1064
Andrei Homescu68a55612022-08-02 01:25:15 +00001065#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001066TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001067 if constexpr (!kEnableSharedLibs) {
1068 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1069 }
1070
Steven Moreland4313d7e2021-07-15 23:41:22 +00001071 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001072
1073 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1074 ASSERT_NE(binder, nullptr);
1075
1076 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1077}
1078
1079TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001080 if constexpr (!kEnableSharedLibs) {
1081 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1082 }
1083
Steven Moreland4313d7e2021-07-15 23:41:22 +00001084 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001085
1086 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1087 ASSERT_NE(binder, nullptr);
1088
1089 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1090 ASSERT_NE(ndkBinder, nullptr);
1091
1092 std::string out;
1093 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1094 ASSERT_TRUE(status.isOk()) << status.getDescription();
1095 ASSERT_EQ("aoeuaoeu", out);
1096}
Andrei Homescu68a55612022-08-02 01:25:15 +00001097#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001098
Steven Moreland5553ac42020-11-11 02:14:45 +00001099ssize_t countFds() {
1100 DIR* dir = opendir("/proc/self/fd/");
1101 if (dir == nullptr) return -1;
1102 ssize_t ret = 0;
1103 dirent* ent;
1104 while ((ent = readdir(dir)) != nullptr) ret++;
1105 closedir(dir);
1106 return ret;
1107}
1108
Andrei Homescua858b0e2022-08-01 23:43:09 +00001109TEST_P(BinderRpc, Fds) {
1110 if (serverSingleThreaded()) {
1111 GTEST_SKIP() << "This test requires multiple threads";
1112 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001113 if (socketType() == SocketType::TIPC) {
1114 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1115 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001116
Steven Moreland5553ac42020-11-11 02:14:45 +00001117 ssize_t beforeFds = countFds();
1118 ASSERT_GE(beforeFds, 0);
1119 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001120 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001121 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1122 }
1123 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1124}
1125
Andrei Homescud65666d2023-03-03 07:28:02 +00001126#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001127
1128static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1129 std::vector<BinderRpc::ParamType> ret;
1130
1131 for (const auto& clientVersion : testVersions()) {
1132 for (const auto& serverVersion : testVersions()) {
1133 ret.push_back(BinderRpc::ParamType{
1134 .type = SocketType::TIPC,
1135 .security = RpcSecurity::RAW,
1136 .clientVersion = clientVersion,
1137 .serverVersion = serverVersion,
1138 .singleThreaded = true,
1139 .noKernel = true,
1140 });
1141 }
1142 }
1143
1144 return ret;
1145}
1146
1147INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
Andrei Homescud65666d2023-03-03 07:28:02 +00001148 BinderRpc::PrintParamInfo);
1149#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001150bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001151 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001152 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001153
Andrei Homescu992a4052022-06-28 21:26:18 +00001154 android::base::unique_fd serverFd(
1155 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001156
1157 if (errno == EAFNOSUPPORT) {
1158 return false;
1159 }
1160
Andrei Homescu992a4052022-06-28 21:26:18 +00001161 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1162
1163 sockaddr_vm serverAddr{
1164 .svm_family = AF_VSOCK,
1165 .svm_port = vsockPort,
1166 .svm_cid = VMADDR_CID_ANY,
1167 };
1168 int ret = TEMP_FAILURE_RETRY(
1169 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1170 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1171 strerror(errno));
1172
1173 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1174 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1175 strerror(errno));
1176
1177 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1178 // to see if the kernel supports it. It's safe to use a blocking
1179 // connect because vsock sockets have a 2 second connection timeout,
1180 // and they return ETIMEDOUT after that.
1181 android::base::unique_fd connectFd(
1182 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1183 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1184 strerror(errno));
1185
1186 bool success = false;
1187 sockaddr_vm connectAddr{
1188 .svm_family = AF_VSOCK,
1189 .svm_port = vsockPort,
1190 .svm_cid = VMADDR_CID_LOCAL,
1191 };
1192 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1193 sizeof(connectAddr)));
1194 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1195 android::base::unique_fd acceptFd;
1196 while (true) {
1197 pollfd pfd[]{
1198 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1199 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1200 };
1201 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1202 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1203
1204 if (pfd[0].revents & POLLIN) {
1205 sockaddr_vm acceptAddr;
1206 socklen_t acceptAddrLen = sizeof(acceptAddr);
1207 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1208 reinterpret_cast<sockaddr*>(&acceptAddr),
1209 &acceptAddrLen, SOCK_CLOEXEC));
1210 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1211 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1212 "Truncated address");
1213
1214 // Store the fd in acceptFd so we keep the connection alive
1215 // while polling connectFd
1216 acceptFd.reset(ret);
1217 }
1218
1219 if (pfd[1].revents & POLLOUT) {
1220 // Connect either succeeded or timed out
1221 int connectErrno;
1222 socklen_t connectErrnoLen = sizeof(connectErrno);
1223 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1224 &connectErrnoLen);
1225 LOG_ALWAYS_FATAL_IF(ret == -1,
1226 "Could not getsockopt() after connect() "
1227 "on non-blocking socket: %s.",
1228 strerror(errno));
1229
1230 // We're done, this is all we wanted
1231 success = connectErrno == 0;
1232 break;
1233 }
1234 }
1235 } else {
1236 success = ret == 0;
1237 }
1238
1239 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1240
1241 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001242}
1243
Yifan Hong1deca4b2021-09-10 16:16:44 -07001244static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001245 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1246 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001247
1248 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001249
Steven Moreland9f250b02023-05-16 23:27:42 +00001250#ifdef __BIONIC__
1251 // Devices may not have vsock support. AVF tests will verify whether they do, but
1252 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001253 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001254#else
1255 // On host machines, we always assume we have vsock loopback. If we don't, the
1256 // subsequent failures will be more clear than showing one now.
1257 static bool hasVsockLoopback = true;
1258#endif
Steven Morelandda573042021-06-12 01:13:45 +00001259
1260 if (hasVsockLoopback) {
1261 ret.push_back(SocketType::VSOCK);
1262 }
1263
1264 return ret;
1265}
1266
Steven Morelandb469f432023-07-28 22:13:47 +00001267static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1268 std::vector<BinderRpc::ParamType> ret;
1269
Steven Morelandf7421432023-07-28 22:41:44 +00001270 constexpr bool full = false;
1271
Steven Morelandb469f432023-07-28 22:13:47 +00001272 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001273 if (full || type == SocketType::UNIX) {
1274 for (const auto& security : RpcSecurityValues()) {
1275 for (const auto& clientVersion : testVersions()) {
1276 for (const auto& serverVersion : testVersions()) {
1277 for (bool singleThreaded : {false, true}) {
1278 for (bool noKernel : {false, true}) {
1279 ret.push_back(BinderRpc::ParamType{
1280 .type = type,
1281 .security = security,
1282 .clientVersion = clientVersion,
1283 .serverVersion = serverVersion,
1284 .singleThreaded = singleThreaded,
1285 .noKernel = noKernel,
1286 });
1287 }
Steven Morelandb469f432023-07-28 22:13:47 +00001288 }
1289 }
1290 }
1291 }
Steven Morelandf7421432023-07-28 22:41:44 +00001292 } else {
1293 ret.push_back(BinderRpc::ParamType{
1294 .type = type,
1295 .security = RpcSecurity::RAW,
1296 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1297 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1298 .singleThreaded = false,
1299 .noKernel = false,
1300 });
Steven Morelandb469f432023-07-28 22:13:47 +00001301 }
1302 }
Steven Morelandf7421432023-07-28 22:41:44 +00001303
Steven Morelandb469f432023-07-28 22:13:47 +00001304 return ret;
1305}
1306
1307INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
Yifan Hong702115c2021-06-24 15:39:18 -07001308 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001309
Yifan Hong702115c2021-06-24 15:39:18 -07001310class BinderRpcServerRootObject
1311 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001312
1313TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1314 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1315 auto setRootObject = [](bool isStrong) -> SetFn {
1316 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1317 };
1318
Yifan Hong702115c2021-06-24 15:39:18 -07001319 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001320 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001321 auto binder1 = sp<BBinder>::make();
1322 IBinder* binderRaw1 = binder1.get();
1323 setRootObject(isStrong1)(server.get(), binder1);
1324 EXPECT_EQ(binderRaw1, server->getRootObject());
1325 binder1.clear();
1326 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1327
1328 auto binder2 = sp<BBinder>::make();
1329 IBinder* binderRaw2 = binder2.get();
1330 setRootObject(isStrong2)(server.get(), binder2);
1331 EXPECT_EQ(binderRaw2, server->getRootObject());
1332 binder2.clear();
1333 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1334}
1335
1336INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001337 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1338 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001339
Yifan Hong1a235852021-05-13 16:07:47 -07001340class OneOffSignal {
1341public:
1342 // If notify() was previously called, or is called within |duration|, return true; else false.
1343 template <typename R, typename P>
1344 bool wait(std::chrono::duration<R, P> duration) {
1345 std::unique_lock<std::mutex> lock(mMutex);
1346 return mCv.wait_for(lock, duration, [this] { return mValue; });
1347 }
1348 void notify() {
1349 std::unique_lock<std::mutex> lock(mMutex);
1350 mValue = true;
1351 lock.unlock();
1352 mCv.notify_all();
1353 }
1354
1355private:
1356 std::mutex mMutex;
1357 std::condition_variable mCv;
1358 bool mValue = false;
1359};
1360
Yifan Hong194acf22021-06-29 18:44:56 -07001361TEST(BinderRpc, Java) {
1362#if !defined(__ANDROID__)
1363 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1364 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1365 "to binderHostDeviceTest. Hence, just disable this test on host.";
1366#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001367 if constexpr (!kEnableKernelIpc) {
1368 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1369 "at build time.";
1370 }
1371
Yifan Hong194acf22021-06-29 18:44:56 -07001372 sp<IServiceManager> sm = defaultServiceManager();
1373 ASSERT_NE(nullptr, sm);
1374 // Any Java service with non-empty getInterfaceDescriptor() would do.
1375 // Let's pick batteryproperties.
1376 auto binder = sm->checkService(String16("batteryproperties"));
1377 ASSERT_NE(nullptr, binder);
1378 auto descriptor = binder->getInterfaceDescriptor();
1379 ASSERT_GE(descriptor.size(), 0);
1380 ASSERT_EQ(OK, binder->pingBinder());
1381
1382 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001383 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001384 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001385 auto socket = rpcServer->releaseServer();
1386
1387 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001388 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1389
Yifan Honge3caaf22022-01-12 14:46:56 -08001390 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1391 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001392 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001393 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1394 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001395 << statusToString(setRpcClientDebugStatus);
1396 GTEST_SKIP();
1397 }
1398
1399 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001400
1401 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001402 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001403 auto rpcBinder = rpcSession->getRootObject();
1404 ASSERT_NE(nullptr, rpcBinder);
1405
1406 ASSERT_EQ(OK, rpcBinder->pingBinder());
1407
1408 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1409 << "getInterfaceDescriptor should not crash system_server";
1410 ASSERT_EQ(OK, rpcBinder->pingBinder());
1411}
1412
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001413class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1414public:
1415 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001416 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001417 std::to_string(std::get<1>(info.param));
1418 }
1419};
1420
1421TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1422 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1423 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001424 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001425 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001426 ASSERT_FALSE(server->hasServer());
1427 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1428 ASSERT_TRUE(server->hasServer());
1429 base::unique_fd retrieved = server->releaseServer();
1430 ASSERT_FALSE(server->hasServer());
1431 ASSERT_EQ(sinkFd, retrieved.get());
1432}
1433
1434TEST_P(BinderRpcServerOnly, Shutdown) {
1435 if constexpr (!kEnableRpcThreads) {
1436 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1437 }
1438
1439 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001440 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001441 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001442 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1443 auto joinEnds = std::make_shared<OneOffSignal>();
1444
1445 // If things are broken and the thread never stops, don't block other tests. Because the thread
1446 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1447 // shared pointers are passed.
1448 std::thread([server, joinEnds] {
1449 server->join();
1450 joinEnds->notify();
1451 }).detach();
1452
1453 bool shutdown = false;
1454 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001455 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001456 if (server->shutdown()) shutdown = true;
1457 }
1458 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1459
1460 ASSERT_TRUE(joinEnds->wait(2s))
1461 << "After server->shutdown() returns true, join() did not stop after 2s";
1462}
1463
Frederick Mayledc07cf82022-05-26 20:30:12 +00001464INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1465 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1466 ::testing::ValuesIn(testVersions())),
1467 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001468
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001469class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001470public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001471 // Only parameterized only server version because `RpcSession` is bypassed
1472 // in the client half of the tests.
1473 using Param =
1474 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001475 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001476
1477 // A server that handles client socket connections.
1478 class Server {
1479 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001480 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1481
Yifan Hong1deca4b2021-09-10 16:16:44 -07001482 explicit Server() {}
1483 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001484 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001485 [[nodiscard]] AssertionResult setUp(
1486 const Param& param,
1487 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001488 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001489 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001490 if (!rpcServer->setProtocolVersion(serverVersion)) {
1491 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1492 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001493 switch (socketType) {
1494 case SocketType::PRECONNECTED: {
1495 return AssertionFailure() << "Not supported by this test";
1496 } break;
1497 case SocketType::UNIX: {
1498 auto addr = allocateSocketAddress();
1499 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1500 if (status != OK) {
1501 return AssertionFailure()
1502 << "setupUnixDomainServer: " << statusToString(status);
1503 }
1504 mConnectToServer = [addr] {
1505 return connectTo(UnixSocketAddress(addr.c_str()));
1506 };
1507 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001508 case SocketType::UNIX_BOOTSTRAP: {
1509 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1510 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1511 return AssertionFailure() << "Socketpair() failed";
1512 }
1513 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1514 std::move(bootstrapFdServer));
1515 if (status != OK) {
1516 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1517 << statusToString(status);
1518 }
1519 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1520 mAcceptConnection = &Server::recvmsgServerConnection;
1521 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1522 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001523 case SocketType::UNIX_RAW: {
1524 auto addr = allocateSocketAddress();
1525 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1526 if (status != OK) {
1527 return AssertionFailure()
1528 << "setupRawSocketServer: " << statusToString(status);
1529 }
1530 mConnectToServer = [addr] {
1531 return connectTo(UnixSocketAddress(addr.c_str()));
1532 };
1533 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001534 case SocketType::VSOCK: {
1535 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001536 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001537 if (status != OK) {
1538 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1539 }
1540 mConnectToServer = [port] {
1541 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1542 };
1543 } break;
1544 case SocketType::INET: {
1545 unsigned int port;
1546 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1547 if (status != OK) {
1548 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1549 }
1550 mConnectToServer = [port] {
1551 const char* addr = kLocalInetAddress;
1552 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1553 if (aiStart == nullptr) return base::unique_fd{};
1554 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1555 auto fd = connectTo(
1556 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1557 if (fd.ok()) return fd;
1558 }
1559 ALOGE("None of the socket address resolved for %s:%u can be connected",
1560 addr, port);
1561 return base::unique_fd{};
1562 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001563 } break;
1564 case SocketType::TIPC: {
1565 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1566 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001567 }
1568 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001569 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001570 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001571 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1572 mSetup = true;
1573 return AssertionSuccess();
1574 }
1575 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1576 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1577 return mCertVerifier;
1578 }
1579 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1580 void start() {
1581 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1582 mThread = std::make_unique<std::thread>(&Server::run, this);
1583 }
David Brazdil21c887c2022-09-23 12:25:18 +01001584
1585 base::unique_fd acceptServerConnection() {
1586 return base::unique_fd(TEMP_FAILURE_RETRY(
1587 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1588 }
1589
1590 base::unique_fd recvmsgServerConnection() {
1591 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1592 int buf;
1593 iovec iov{&buf, sizeof(buf)};
1594
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001595 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
David Brazdil21c887c2022-09-23 12:25:18 +01001596 int savedErrno = errno;
1597 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1598 }
1599 if (fds.size() != 1) {
1600 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1601 }
1602 return std::move(std::get<base::unique_fd>(fds[0]));
1603 }
1604
Yifan Hong1deca4b2021-09-10 16:16:44 -07001605 void run() {
1606 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1607
1608 std::vector<std::thread> threads;
1609 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001610 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001611 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1612 }
1613
1614 for (auto& thread : threads) thread.join();
1615 }
1616 void handleOne(android::base::unique_fd acceptedFd) {
1617 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001618 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001619 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001621 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001622 }
Yifan Honge07d2732021-09-13 21:59:14 -07001623 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001624 shutdown();
1625 join();
1626 }
1627 void shutdown() { mFdTrigger->trigger(); }
1628
1629 void setPostConnect(
1630 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1631 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001632 }
1633
1634 private:
1635 std::unique_ptr<std::thread> mThread;
1636 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001637 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001638 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001639 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 std::unique_ptr<RpcTransportCtx> mCtx;
1641 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1642 std::make_shared<RpcCertificateVerifierSimple>();
1643 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001644 // The function invoked after connection and handshake. By default, it is
1645 // |defaultPostConnect| that sends |kMessage| to the client.
1646 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1647 Server::defaultPostConnect;
1648
1649 void join() {
1650 if (mThread != nullptr) {
1651 mThread->join();
1652 mThread = nullptr;
1653 }
1654 }
1655
1656 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1657 FdTrigger* fdTrigger) {
1658 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001659 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001660 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001661 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001662 if (status != OK) return AssertionFailure() << statusToString(status);
1663 return AssertionSuccess();
1664 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001665 };
1666
1667 class Client {
1668 public:
1669 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1670 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001671 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001672 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1673 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001674 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001675 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001676 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1677 return AssertionSuccess();
1678 }
1679 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1680 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1681 return mCertVerifier;
1682 }
Yifan Hong67519322021-09-13 18:51:16 -07001683 // connect() and do handshake
1684 bool setUpTransport() {
1685 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001686 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001687 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1688 return mClientTransport != nullptr;
1689 }
1690 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1691 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1692 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001693 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001694 status_t readStatus =
1695 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001696 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001697 if (readStatus != OK) {
1698 return AssertionFailure() << statusToString(readStatus);
1699 }
1700 if (readMessage != expectedMessage) {
1701 return AssertionFailure()
1702 << "Expected " << expectedMessage << ", actual " << readMessage;
1703 }
1704 return AssertionSuccess();
1705 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001706 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001707 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001708 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1709 return;
1710 }
1711 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001712 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001713 }
1714
Pawan49d74cb2022-08-03 21:19:11 +00001715 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1716
Yifan Hong1deca4b2021-09-10 16:16:44 -07001717 private:
1718 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001719 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001720 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1721 std::unique_ptr<RpcTransportCtx> mCtx;
1722 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1723 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001724 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001725 };
1726
1727 // Make A trust B.
1728 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001729 static status_t trust(RpcSecurity rpcSecurity,
1730 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1731 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001732 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001733 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1734 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1735 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736 }
1737
1738 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001739};
1740
1741class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1742public:
1743 using Server = RpcTransportTestUtils::Server;
1744 using Client = RpcTransportTestUtils::Client;
1745 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001746 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001747 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001748 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001749 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001750 return ret;
1751 }
1752 static std::vector<ParamType> getRpcTranportTestParams() {
1753 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001754 for (auto serverVersion : testVersions()) {
1755 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1756 for (auto rpcSecurity : RpcSecurityValues()) {
1757 switch (rpcSecurity) {
1758 case RpcSecurity::RAW: {
1759 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1760 } break;
1761 case RpcSecurity::TLS: {
1762 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1763 serverVersion);
1764 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1765 serverVersion);
1766 } break;
1767 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001768 }
1769 }
1770 }
1771 return ret;
1772 }
1773 template <typename A, typename B>
1774 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001775 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1776 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001777 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1778 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001779 void SetUp() override {
1780 if constexpr (!kEnableRpcThreads) {
1781 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1782 }
1783 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001784};
1785
1786TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001787 auto server = std::make_unique<Server>();
1788 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001789
1790 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001791 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001792
1793 ASSERT_EQ(OK, trust(&client, server));
1794 ASSERT_EQ(OK, trust(server, &client));
1795
1796 server->start();
1797 client.run();
1798}
1799
1800TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001801 auto server = std::make_unique<Server>();
1802 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001803
1804 std::vector<Client> clients;
1805 for (int i = 0; i < 2; i++) {
1806 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001807 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001808 ASSERT_EQ(OK, trust(&client, server));
1809 ASSERT_EQ(OK, trust(server, &client));
1810 }
1811
1812 server->start();
1813 for (auto& client : clients) client.run();
1814}
1815
1816TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001817 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1818 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001819
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001820 auto untrustedServer = std::make_unique<Server>();
1821 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001822
1823 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001824 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001825
1826 ASSERT_EQ(OK, trust(untrustedServer, &client));
1827
1828 untrustedServer->start();
1829
1830 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1831 // the client can't verify the server's identity.
1832 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1833 client.run(handshakeOk);
1834}
1835TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001836 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1837 (void)serverVersion;
1838
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 auto validServer = std::make_unique<Server>();
1840 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001841
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001842 auto maliciousServer = std::make_unique<Server>();
1843 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844
1845 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001846 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001847
1848 ASSERT_EQ(OK, trust(&client, validServer));
1849 ASSERT_EQ(OK, trust(validServer, &client));
1850 ASSERT_EQ(OK, trust(maliciousServer, &client));
1851
1852 maliciousServer->start();
1853
1854 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1855 // the client can't verify the server's identity.
1856 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1857 client.run(handshakeOk);
1858}
1859
1860TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001861 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1862 (void)serverVersion;
1863
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001864 auto server = std::make_unique<Server>();
1865 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001866
1867 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001868 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869
1870 ASSERT_EQ(OK, trust(&client, server));
1871
1872 server->start();
1873
1874 // For TLS, Client should be able to verify server's identity, so client should see
1875 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1876 // identity and should drop the connection, so client shouldn't be able to read anything.
1877 bool readOk = rpcSecurity != RpcSecurity::TLS;
1878 client.run(true, readOk);
1879}
1880
1881TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001882 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1883 (void)serverVersion;
1884
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001885 auto server = std::make_unique<Server>();
1886 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001887
1888 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001889 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001890 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001891 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001892
1893 ASSERT_EQ(OK, trust(&validClient, server));
1894 ASSERT_EQ(OK, trust(&maliciousClient, server));
1895
1896 server->start();
1897
1898 // See UntrustedClient.
1899 bool readOk = rpcSecurity != RpcSecurity::TLS;
1900 maliciousClient.run(true, readOk);
1901}
1902
Yifan Hong67519322021-09-13 18:51:16 -07001903TEST_P(RpcTransportTest, Trigger) {
1904 std::string msg2 = ", world!";
1905 std::mutex writeMutex;
1906 std::condition_variable writeCv;
1907 bool shouldContinueWriting = false;
1908 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001909 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001910 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001911 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1912 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001913 if (status != OK) return AssertionFailure() << statusToString(status);
1914
1915 {
1916 std::unique_lock<std::mutex> lock(writeMutex);
1917 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1918 return AssertionFailure() << "write barrier not cleared in time!";
1919 }
1920 }
1921
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001922 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001923 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1924 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001925 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001926 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001927 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001928 << statusToString(status);
1929 return AssertionSuccess();
1930 };
1931
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001932 auto server = std::make_unique<Server>();
1933 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001934
1935 // Set up client
1936 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001938
1939 // Exchange keys
1940 ASSERT_EQ(OK, trust(&client, server));
1941 ASSERT_EQ(OK, trust(server, &client));
1942
1943 server->setPostConnect(serverPostConnect);
1944
Yifan Hong67519322021-09-13 18:51:16 -07001945 server->start();
1946 // connect() to server and do handshake
1947 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001948 // read the first message. This ensures that server has finished handshake and start handling
1949 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001950 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001951 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1952 // write is on an FdTrigger that has been shut down.
1953 server->shutdown();
1954 // Continues server thread to write the second message.
1955 {
Yifan Hong22211f82021-09-14 12:32:25 -07001956 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001957 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001958 }
Yifan Hong22211f82021-09-14 12:32:25 -07001959 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001960 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001961 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001962 // On the client side, second read fails with DEAD_OBJECT
1963 ASSERT_FALSE(client.readMessage(msg2));
1964}
1965
Pawan49d74cb2022-08-03 21:19:11 +00001966TEST_P(RpcTransportTest, CheckWaitingForRead) {
1967 std::mutex readMutex;
1968 std::condition_variable readCv;
1969 bool shouldContinueReading = false;
1970 // Server will write data on transport once its started
1971 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1972 std::string message(RpcTransportTestUtils::kMessage);
1973 iovec messageIov{message.data(), message.size()};
1974 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1975 std::nullopt, nullptr);
1976 if (status != OK) return AssertionFailure() << statusToString(status);
1977
1978 {
1979 std::unique_lock<std::mutex> lock(readMutex);
1980 shouldContinueReading = true;
1981 lock.unlock();
1982 readCv.notify_all();
1983 }
1984 return AssertionSuccess();
1985 };
1986
1987 // Setup Server and client
1988 auto server = std::make_unique<Server>();
1989 ASSERT_TRUE(server->setUp(GetParam()));
1990
1991 Client client(server->getConnectToServerFn());
1992 ASSERT_TRUE(client.setUp(GetParam()));
1993
1994 ASSERT_EQ(OK, trust(&client, server));
1995 ASSERT_EQ(OK, trust(server, &client));
1996 server->setPostConnect(serverPostConnect);
1997
1998 server->start();
1999 ASSERT_TRUE(client.setUpTransport());
2000 {
2001 // Wait till server writes data
2002 std::unique_lock<std::mutex> lock(readMutex);
2003 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2004 }
2005
2006 // Since there is no read polling here, we will get polling count 0
2007 ASSERT_FALSE(client.isTransportWaiting());
2008 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2009 // Thread should increment polling count, read and decrement polling count
2010 // Again, polling count should be zero here
2011 ASSERT_FALSE(client.isTransportWaiting());
2012
2013 server->shutdown();
2014}
2015
Yifan Hong1deca4b2021-09-10 16:16:44 -07002016INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002017 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002018 RpcTransportTest::PrintParamInfo);
2019
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002020class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002021 : public testing::TestWithParam<
2022 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023public:
2024 template <typename A, typename B>
2025 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002026 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2027 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002028 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2029 }
2030 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002031 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2032 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2033 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002034 };
2035};
2036
2037TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002038 if constexpr (!kEnableRpcThreads) {
2039 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2040 }
2041
Frederick Mayledc07cf82022-05-26 20:30:12 +00002042 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002043
2044 std::vector<uint8_t> pkeyData, certData;
2045 {
2046 auto pkey = makeKeyPairForSelfSignedCert();
2047 ASSERT_NE(nullptr, pkey);
2048 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2049 ASSERT_NE(nullptr, cert);
2050 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2051 certData = serializeCertificate(cert.get(), certificateFormat);
2052 }
2053
2054 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2055 auto desCert = deserializeCertificate(certData, certificateFormat);
2056 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002057 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2058 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002059
2060 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2061 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2062
2063 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2064 ASSERT_TRUE(client.setUp(utilsParam));
2065
2066 ASSERT_EQ(OK, trust(&client, server));
2067 ASSERT_EQ(OK, trust(server, &client));
2068
2069 server->start();
2070 client.run();
2071}
2072
2073INSTANTIATE_TEST_CASE_P(
2074 BinderRpc, RpcTransportTlsKeyTest,
2075 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2076 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002077 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2078 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002079 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002080#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002081
Steven Morelandc1635952021-04-01 16:20:47 +00002082} // namespace android
2083
2084int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002085 ::testing::InitGoogleTest(&argc, argv);
2086 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002087
Steven Moreland5553ac42020-11-11 02:14:45 +00002088 return RUN_ALL_TESTS();
2089}