blob: 36c8d8cd503a0d5b826428661b1bab0bed2dd70b [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
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000032#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000033
Yifan Hong1a235852021-05-13 16:07:47 -070034using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070035using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070036using testing::AssertionFailure;
37using testing::AssertionResult;
38using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070039
Steven Moreland5553ac42020-11-11 02:14:45 +000040namespace android {
41
Andrei Homescu12106de2022-04-27 04:42:21 +000042#ifdef BINDER_TEST_NO_SHARED_LIBS
43constexpr bool kEnableSharedLibs = false;
44#else
45constexpr bool kEnableSharedLibs = true;
46#endif
47
Frederick Maylea12b0962022-06-25 01:13:22 +000048static std::string WaitStatusToString(int wstatus) {
49 if (WIFEXITED(wstatus)) {
50 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
51 }
52 if (WIFSIGNALED(wstatus)) {
53 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
54 }
55 return base::StringPrintf("unexpected state %d", wstatus);
56}
57
Steven Moreland276d8df2022-09-28 23:56:39 +000058static void debugBacktrace(pid_t pid) {
59 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
60 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
61}
62
Steven Moreland5553ac42020-11-11 02:14:45 +000063class Process {
64public:
Andrei Homescu96834632022-10-14 00:49:49 +000065 Process(Process&& other)
66 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
67 mReadEnd(std::move(other.mReadEnd)),
68 mWriteEnd(std::move(other.mWriteEnd)) {
69 // The default move constructor doesn't clear mPid after moving it,
70 // which we need to do because the destructor checks for mPid!=0
71 mPid = other.mPid;
72 other.mPid = 0;
73 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070074 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
75 android::base::borrowed_fd /* readEnd */)>& f) {
76 android::base::unique_fd childWriteEnd;
77 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000078 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
79 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000080 if (0 == (mPid = fork())) {
81 // racey: assume parent doesn't crash before this is set
82 prctl(PR_SET_PDEATHSIG, SIGHUP);
83
Yifan Hong1deca4b2021-09-10 16:16:44 -070084 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000085
86 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000087 }
88 }
89 ~Process() {
90 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +000091 int wstatus;
92 waitpid(mPid, &wstatus, 0);
93 if (mCustomExitStatusCheck) {
94 mCustomExitStatusCheck(wstatus);
95 } else {
96 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
97 << "server process failed: " << WaitStatusToString(wstatus);
98 }
Steven Moreland5553ac42020-11-11 02:14:45 +000099 }
100 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700101 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700102 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000103
Frederick Maylea12b0962022-06-25 01:13:22 +0000104 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
105 mCustomExitStatusCheck = std::move(f);
106 }
107
Frederick Mayle69a0c992022-05-26 20:38:39 +0000108 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
109 void terminate() { kill(mPid, SIGTERM); }
110
Steven Moreland276d8df2022-09-28 23:56:39 +0000111 pid_t getPid() { return mPid; }
112
Steven Moreland5553ac42020-11-11 02:14:45 +0000113private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000114 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000115 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700116 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700117 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000118};
119
120static std::string allocateSocketAddress() {
121 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000122 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700123 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
124 unlink(ret.c_str());
125 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000126};
127
Steven Morelandda573042021-06-12 01:13:45 +0000128static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000129 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000130 return vsockPort++;
131}
132
Alice Wang893a9912022-10-24 10:44:09 +0000133static base::unique_fd initUnixSocket(std::string addr) {
134 auto socket_addr = UnixSocketAddress(addr.c_str());
135 base::unique_fd fd(
136 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
137 CHECK(fd.ok());
138 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
139 return fd;
140}
141
Andrei Homescu96834632022-10-14 00:49:49 +0000142// Destructors need to be defined, even if pure virtual
143ProcessSession::~ProcessSession() {}
144
145class LinuxProcessSession : public ProcessSession {
146public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000147 // reference to process hosting a socket server
148 Process host;
149
Andrei Homescu96834632022-10-14 00:49:49 +0000150 LinuxProcessSession(LinuxProcessSession&&) = default;
151 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
152 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 for (auto& session : sessions) {
154 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000155 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000156
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157 for (auto& info : sessions) {
158 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000159
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000160 EXPECT_NE(nullptr, session);
161 EXPECT_NE(nullptr, session->state());
162 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000163
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 wp<RpcSession> weakSession = session;
165 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000166
Steven Moreland57042712022-10-04 23:56:45 +0000167 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
168 // the object should not actually be promotable. By looping, we distinguish a race here
169 // from a bug causing the object to not be promotable.
170 for (size_t i = 0; i < 3; i++) {
171 sp<RpcSession> strongSession = weakSession.promote();
172 EXPECT_EQ(nullptr, strongSession)
173 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
174 "Leaked sess: ")
175 << strongSession->getStrongCount() << " checked time " << i;
176
177 if (strongSession != nullptr) {
178 sleep(1);
179 }
180 }
Steven Moreland736664b2021-05-01 04:27:25 +0000181 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000182 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000183
Andrei Homescu96834632022-10-14 00:49:49 +0000184 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
185 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000186 }
Andrei Homescu96834632022-10-14 00:49:49 +0000187
188 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000189};
190
Yifan Hong1deca4b2021-09-10 16:16:44 -0700191static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700192 base::unique_fd serverFd(
193 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
194 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700195 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
196 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700197
198 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
199 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700200 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
201 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700202 }
203 return serverFd;
204}
205
David Brazdil21c887c2022-09-23 12:25:18 +0100206static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
207 base::unique_fd sockClient, sockServer;
208 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
209 int savedErrno = errno;
210 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
211 }
212
213 int zero = 0;
214 iovec iov{&zero, sizeof(zero)};
215 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
216 fds.emplace_back(std::move(sockServer));
217
218 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
219 int savedErrno = errno;
220 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
221 }
222 return std::move(sockClient);
223}
224
Andrei Homescu96834632022-10-14 00:49:49 +0000225std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
226 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
227 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
228 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
229 if (singleThreaded) {
230 ret += "_single_threaded";
231 }
232 if (noKernel) {
233 ret += "_no_kernel";
234 }
235 return ret;
236}
Andrei Homescu2a298012022-06-15 01:08:54 +0000237
Andrei Homescu96834632022-10-14 00:49:49 +0000238// This creates a new process serving an interface on a certain number of
239// threads.
240std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
241 const BinderRpcOptions& options) {
242 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000243
Andrei Homescu96834632022-10-14 00:49:49 +0000244 SocketType socketType = std::get<0>(GetParam());
245 RpcSecurity rpcSecurity = std::get<1>(GetParam());
246 uint32_t clientVersion = std::get<2>(GetParam());
247 uint32_t serverVersion = std::get<3>(GetParam());
248 bool singleThreaded = std::get<4>(GetParam());
249 bool noKernel = std::get<5>(GetParam());
250
251 std::string path = android::base::GetExecutableDirectory();
252 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
253 singleThreaded ? "_single_threaded" : "",
254 noKernel ? "_no_kernel" : "");
255
Alice Wang1ef010b2022-11-14 09:09:25 +0000256 base::unique_fd bootstrapClientFd, socketFd;
257
Alice Wang893a9912022-10-24 10:44:09 +0000258 auto addr = allocateSocketAddress();
259 // Initializes the socket before the fork/exec.
260 if (socketType == SocketType::UNIX_RAW) {
261 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000262 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
263 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
264 // This is because we cannot pass ParcelFileDescriptor over a pipe.
265 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
266 int savedErrno = errno;
267 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
268 }
Alice Wang893a9912022-10-24 10:44:09 +0000269 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000270
Andrei Homescu96834632022-10-14 00:49:49 +0000271 auto ret = std::make_unique<LinuxProcessSession>(
272 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
273 auto writeFd = std::to_string(writeEnd.get());
274 auto readFd = std::to_string(readEnd.get());
275 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
276 NULL);
277 }));
278
279 BinderRpcTestServerConfig serverConfig;
280 serverConfig.numThreads = options.numThreads;
281 serverConfig.socketType = static_cast<int32_t>(socketType);
282 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
283 serverConfig.serverVersion = serverVersion;
284 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000285 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000286 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000287 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
288 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
289 static_cast<int32_t>(mode));
290 }
291 writeToFd(ret->host.writeEnd(), serverConfig);
292
293 std::vector<sp<RpcSession>> sessions;
294 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
295 for (size_t i = 0; i < options.numSessions; i++) {
296 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
David Brazdil21c887c2022-09-23 12:25:18 +0100297 }
298
Andrei Homescu96834632022-10-14 00:49:49 +0000299 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
300 BinderRpcTestClientInfo clientInfo;
301 for (const auto& session : sessions) {
302 auto& parcelableCert = clientInfo.certs.emplace_back();
303 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
304 }
305 writeToFd(ret->host.writeEnd(), clientInfo);
306
307 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
308 if (socketType == SocketType::INET) {
309 CHECK_NE(0, serverInfo.port);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000310 }
311
Andrei Homescu96834632022-10-14 00:49:49 +0000312 if (rpcSecurity == RpcSecurity::TLS) {
313 const auto& serverCert = serverInfo.cert.data;
314 CHECK_EQ(OK,
315 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700316 }
317
Andrei Homescu96834632022-10-14 00:49:49 +0000318 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000319
Andrei Homescu96834632022-10-14 00:49:49 +0000320 for (const auto& session : sessions) {
321 CHECK(session->setProtocolVersion(clientVersion));
322 session->setMaxIncomingThreads(options.numIncomingConnections);
323 session->setMaxOutgoingThreads(options.numOutgoingConnections);
324 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000325
Andrei Homescu96834632022-10-14 00:49:49 +0000326 switch (socketType) {
327 case SocketType::PRECONNECTED:
328 status = session->setupPreconnectedClient({}, [=]() {
329 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
330 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000331 break;
Alice Wang893a9912022-10-24 10:44:09 +0000332 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000333 case SocketType::UNIX:
334 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
335 break;
336 case SocketType::UNIX_BOOTSTRAP:
337 status = session->setupUnixDomainSocketBootstrapClient(
338 base::unique_fd(dup(bootstrapClientFd.get())));
339 break;
340 case SocketType::VSOCK:
341 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
342 break;
343 case SocketType::INET:
344 status = session->setupInetClient("127.0.0.1", serverInfo.port);
345 break;
346 default:
347 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000348 }
Andrei Homescu96834632022-10-14 00:49:49 +0000349 if (options.allowConnectFailure && status != OK) {
350 ret->sessions.clear();
351 break;
352 }
353 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
354 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000355 }
Andrei Homescu96834632022-10-14 00:49:49 +0000356 return ret;
357}
Steven Morelandc1635952021-04-01 16:20:47 +0000358
Andrei Homescua858b0e2022-08-01 23:43:09 +0000359TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
360 if (clientOrServerSingleThreaded()) {
361 GTEST_SKIP() << "This test requires multiple threads";
362 }
363
Steven Moreland5553ac42020-11-11 02:14:45 +0000364 constexpr size_t kNumThreads = 10;
365
Steven Moreland4313d7e2021-07-15 23:41:22 +0000366 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000367
368 EXPECT_OK(proc.rootIface->lock());
369
370 // block all but one thread taking locks
371 std::vector<std::thread> ts;
372 for (size_t i = 0; i < kNumThreads - 1; i++) {
373 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
374 }
375
Steven Morelandd6d816f2022-12-23 01:37:17 +0000376 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000377
378 // other calls still work
379 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
380
Steven Morelandd6d816f2022-12-23 01:37:17 +0000381 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000382 size_t epochMsBefore = epochMillis();
383 // after this, we should never see a response within this time
384 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
385
386 // this call should be blocked for blockTimeMs
387 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
388
389 size_t epochMsAfter = epochMillis();
390 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
391
392 for (auto& t : ts) t.join();
393}
394
Andrei Homescu96834632022-10-14 00:49:49 +0000395static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
396 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000397 size_t epochMsBefore = epochMillis();
398
399 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700400 for (size_t i = 0; i < numCalls; i++) {
401 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 }
403
404 for (auto& t : ts) t.join();
405
406 size_t epochMsAfter = epochMillis();
407
Yifan Hong1f44f982021-10-08 17:16:47 -0700408 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000409
410 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700411 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
412}
413
Andrei Homescua858b0e2022-08-01 23:43:09 +0000414TEST_P(BinderRpc, ThreadPoolOverSaturated) {
415 if (clientOrServerSingleThreaded()) {
416 GTEST_SKIP() << "This test requires multiple threads";
417 }
418
Yifan Hong1f44f982021-10-08 17:16:47 -0700419 constexpr size_t kNumThreads = 10;
420 constexpr size_t kNumCalls = kNumThreads + 3;
421 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
422 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
423}
424
Andrei Homescua858b0e2022-08-01 23:43:09 +0000425TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
426 if (clientOrServerSingleThreaded()) {
427 GTEST_SKIP() << "This test requires multiple threads";
428 }
429
Yifan Hong1f44f982021-10-08 17:16:47 -0700430 constexpr size_t kNumThreads = 20;
431 constexpr size_t kNumOutgoingConnections = 10;
432 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
433 auto proc = createRpcTestSocketServerProcess(
434 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
435 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000436}
437
Andrei Homescua858b0e2022-08-01 23:43:09 +0000438TEST_P(BinderRpc, ThreadingStressTest) {
439 if (clientOrServerSingleThreaded()) {
440 GTEST_SKIP() << "This test requires multiple threads";
441 }
442
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 constexpr size_t kNumClientThreads = 10;
444 constexpr size_t kNumServerThreads = 10;
445 constexpr size_t kNumCalls = 100;
446
Steven Moreland4313d7e2021-07-15 23:41:22 +0000447 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000448
449 std::vector<std::thread> threads;
450 for (size_t i = 0; i < kNumClientThreads; i++) {
451 threads.push_back(std::thread([&] {
452 for (size_t j = 0; j < kNumCalls; j++) {
453 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000454 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 EXPECT_EQ(proc.rootBinder, out);
456 }
457 }));
458 }
459
460 for (auto& t : threads) t.join();
461}
462
Steven Moreland925ba0a2021-09-17 18:06:32 -0700463static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
464 std::vector<std::thread> threads;
465 for (size_t i = 0; i < threadCount; i++) {
466 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
467 }
468 for (auto& t : threads) t.join();
469}
470
Andrei Homescua858b0e2022-08-01 23:43:09 +0000471TEST_P(BinderRpc, OnewayStressTest) {
472 if (clientOrServerSingleThreaded()) {
473 GTEST_SKIP() << "This test requires multiple threads";
474 }
475
Steven Morelandc6046982021-04-20 00:49:42 +0000476 constexpr size_t kNumClientThreads = 10;
477 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700478 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000479
Steven Moreland4313d7e2021-07-15 23:41:22 +0000480 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000481
482 std::vector<std::thread> threads;
483 for (size_t i = 0; i < kNumClientThreads; i++) {
484 threads.push_back(std::thread([&] {
485 for (size_t j = 0; j < kNumCalls; j++) {
486 EXPECT_OK(proc.rootIface->sendString("a"));
487 }
Steven Morelandc6046982021-04-20 00:49:42 +0000488 }));
489 }
490
491 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700492
493 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000494}
495
Frederick Mayleb0221d12022-10-03 23:10:53 +0000496TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
497 if (!supportsFdTransport()) {
498 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
499 }
500 if (clientOrServerSingleThreaded()) {
501 GTEST_SKIP() << "This test requires multiple threads";
502 }
503
504 // This test forces a oneway transaction to be queued by issuing two
505 // `blockingSendFdOneway` calls, then drains the queue by issuing two
506 // `blockingRecvFd` calls.
507 //
508 // For more details about the queuing semantics see
509 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
510
511 auto proc = createRpcTestSocketServerProcess({
512 .numThreads = 3,
513 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
514 .serverSupportedFileDescriptorTransportModes =
515 {RpcSession::FileDescriptorTransportMode::UNIX},
516 });
517
518 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
519 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
520 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
521 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
522
523 android::os::ParcelFileDescriptor fdA;
524 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
525 std::string result;
526 CHECK(android::base::ReadFdToString(fdA.get(), &result));
527 EXPECT_EQ(result, "a");
528
529 android::os::ParcelFileDescriptor fdB;
530 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
531 CHECK(android::base::ReadFdToString(fdB.get(), &result));
532 EXPECT_EQ(result, "b");
533}
534
Andrei Homescua858b0e2022-08-01 23:43:09 +0000535TEST_P(BinderRpc, OnewayCallQueueing) {
536 if (clientOrServerSingleThreaded()) {
537 GTEST_SKIP() << "This test requires multiple threads";
538 }
539
Steven Moreland5553ac42020-11-11 02:14:45 +0000540 constexpr size_t kNumSleeps = 10;
541 constexpr size_t kNumExtraServerThreads = 4;
542 constexpr size_t kSleepMs = 50;
543
544 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000545 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000546
547 EXPECT_OK(proc.rootIface->lock());
548
Steven Moreland1c678802021-09-17 16:48:47 -0700549 size_t epochMsBefore = epochMillis();
550
551 // all these *Async commands should be queued on the server sequentially,
552 // even though there are multiple threads.
553 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 proc.rootIface->sleepMsAsync(kSleepMs);
555 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000556 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
557
Steven Moreland1c678802021-09-17 16:48:47 -0700558 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700560
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 size_t epochMsAfter = epochMillis();
562
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000563 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000564
Steven Moreland925ba0a2021-09-17 18:06:32 -0700565 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000566}
567
Andrei Homescua858b0e2022-08-01 23:43:09 +0000568TEST_P(BinderRpc, OnewayCallExhaustion) {
569 if (clientOrServerSingleThreaded()) {
570 GTEST_SKIP() << "This test requires multiple threads";
571 }
572
Steven Morelandd45be622021-06-04 02:19:37 +0000573 constexpr size_t kNumClients = 2;
574 constexpr size_t kTooLongMs = 1000;
575
Steven Moreland4313d7e2021-07-15 23:41:22 +0000576 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000577
578 // Build up oneway calls on the second session to make sure it terminates
579 // and shuts down. The first session should be unaffected (proc destructor
580 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000581 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000582
583 std::vector<std::thread> threads;
584 for (size_t i = 0; i < kNumClients; i++) {
585 // one of these threads will get stuck queueing a transaction once the
586 // socket fills up, the other will be able to fill up transactions on
587 // this object
588 threads.push_back(std::thread([&] {
589 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
590 }
591 }));
592 }
593 for (auto& t : threads) t.join();
594
595 Status status = iface->sleepMsAsync(kTooLongMs);
596 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
597
Steven Moreland798e0d12021-07-14 23:19:25 +0000598 // now that it has died, wait for the remote session to shutdown
599 std::vector<int32_t> remoteCounts;
600 do {
601 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
602 } while (remoteCounts.size() == kNumClients);
603
Steven Morelandd45be622021-06-04 02:19:37 +0000604 // the second session should be shutdown in the other process by the time we
605 // are able to join above (it'll only be hung up once it finishes processing
606 // any pending commands). We need to erase this session from the record
607 // here, so that the destructor for our session won't check that this
608 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000609 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000610}
611
Devin Moore66d5b7a2022-07-07 21:42:10 +0000612TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000613 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000614 GTEST_SKIP() << "This test requires multiple threads";
615 }
616 class MyDeathRec : public IBinder::DeathRecipient {
617 public:
618 void binderDied(const wp<IBinder>& /* who */) override {
619 dead = true;
620 mCv.notify_one();
621 }
622 std::mutex mMtx;
623 std::condition_variable mCv;
624 bool dead = false;
625 };
626
627 // Death recipient needs to have an incoming connection to be called
628 auto proc = createRpcTestSocketServerProcess(
629 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
630
631 auto dr = sp<MyDeathRec>::make();
632 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
633
634 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
635 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
636 }
637
638 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000639 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000640
641 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000642 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000643 proc.expectAlreadyShutdown = true;
644}
645
646TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000647 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000648 GTEST_SKIP() << "This test requires multiple threads";
649 }
650 class MyDeathRec : public IBinder::DeathRecipient {
651 public:
652 void binderDied(const wp<IBinder>& /* who */) override {
653 dead = true;
654 mCv.notify_one();
655 }
656 std::mutex mMtx;
657 std::condition_variable mCv;
658 bool dead = false;
659 };
660
661 // Death recipient needs to have an incoming connection to be called
662 auto proc = createRpcTestSocketServerProcess(
663 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
664
665 auto dr = sp<MyDeathRec>::make();
666 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
667
668 // Explicitly calling shutDownAndWait will cause the death recipients
669 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000670 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000671
672 std::unique_lock<std::mutex> lock(dr->mMtx);
673 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000674 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000675 }
676 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
677
Andrei Homescu96834632022-10-14 00:49:49 +0000678 proc.proc->terminate();
679 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000680 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
681 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
682 });
683 proc.expectAlreadyShutdown = true;
684}
685
Steven Moreland5ec743f2023-01-18 01:02:06 +0000686TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000687 class MyDeathRec : public IBinder::DeathRecipient {
688 public:
689 void binderDied(const wp<IBinder>& /* who */) override {}
690 };
691
692 auto proc = createRpcTestSocketServerProcess(
693 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
694
695 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000696 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000697}
698
699TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000700 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000701 GTEST_SKIP() << "This test requires multiple threads";
702 }
703 class MyDeathRec : public IBinder::DeathRecipient {
704 public:
705 void binderDied(const wp<IBinder>& /* who */) override {
706 GTEST_FAIL() << "This should not be called after unlinkToDeath";
707 }
708 };
709
710 // Death recipient needs to have an incoming connection to be called
711 auto proc = createRpcTestSocketServerProcess(
712 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
713
714 auto dr = sp<MyDeathRec>::make();
715 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
716 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
717
718 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
719 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
720 }
721
722 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000723 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000724 proc.expectAlreadyShutdown = true;
725}
726
Steven Morelandc1635952021-04-01 16:20:47 +0000727TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000728 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000729 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000730
731 // make sure there is some state during crash
732 // 1. we hold their binder
733 sp<IBinderRpcSession> session;
734 EXPECT_OK(proc.rootIface->openSession("happy", &session));
735 // 2. they hold our binder
736 sp<IBinder> binder = new BBinder();
737 EXPECT_OK(proc.rootIface->holdBinder(binder));
738
739 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
740 << "Do death cleanup: " << doDeathCleanup;
741
Andrei Homescu96834632022-10-14 00:49:49 +0000742 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000743 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
744 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
745 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000746 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000747 }
748}
749
Steven Morelandd7302072021-05-15 01:32:04 +0000750TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000751 // This test only works if the current process shared the internal state of
752 // ProcessState with the service across the call to fork(). Both the static
753 // libraries and libbinder.so have their own separate copies of all the
754 // globals, so the test only works when the test client and service both use
755 // libbinder.so (when using static libraries, even a client and service
756 // using the same kind of static library should have separate copies of the
757 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000758 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000759 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
760 "at build time.";
761 }
762
Steven Moreland4313d7e2021-07-15 23:41:22 +0000763 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000764
Andrei Homescu2a298012022-06-15 01:08:54 +0000765 // we can't allocate IPCThreadState so actually the first time should
766 // succeed :(
767 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000768
769 // second time! we catch the error :)
770 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
771
Andrei Homescu96834632022-10-14 00:49:49 +0000772 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000773 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
774 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
775 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000776 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000777}
778
Frederick Mayle69a0c992022-05-26 20:38:39 +0000779TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
780 auto proc = createRpcTestSocketServerProcess({
781 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
782 .serverSupportedFileDescriptorTransportModes =
783 {RpcSession::FileDescriptorTransportMode::UNIX},
784 .allowConnectFailure = true,
785 });
Andrei Homescu96834632022-10-14 00:49:49 +0000786 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
787 proc.proc->terminate();
788 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000789 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
790 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
791 });
792 proc.expectAlreadyShutdown = true;
793}
794
795TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
796 auto proc = createRpcTestSocketServerProcess({
797 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
798 .serverSupportedFileDescriptorTransportModes =
799 {RpcSession::FileDescriptorTransportMode::NONE},
800 .allowConnectFailure = true,
801 });
Andrei Homescu96834632022-10-14 00:49:49 +0000802 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
803 proc.proc->terminate();
804 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000805 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
806 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
807 });
808 proc.expectAlreadyShutdown = true;
809}
810
811TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
812 auto proc = createRpcTestSocketServerProcess({
813 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
814 .serverSupportedFileDescriptorTransportModes =
815 {RpcSession::FileDescriptorTransportMode::NONE,
816 RpcSession::FileDescriptorTransportMode::UNIX},
817 });
818
819 android::os::ParcelFileDescriptor out;
820 auto status = proc.rootIface->echoAsFile("hello", &out);
821 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
822}
823
824TEST_P(BinderRpc, ReceiveFile) {
825 auto proc = createRpcTestSocketServerProcess({
826 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
827 .serverSupportedFileDescriptorTransportModes =
828 {RpcSession::FileDescriptorTransportMode::UNIX},
829 });
830
831 android::os::ParcelFileDescriptor out;
832 auto status = proc.rootIface->echoAsFile("hello", &out);
833 if (!supportsFdTransport()) {
834 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
835 return;
836 }
837 ASSERT_TRUE(status.isOk()) << status;
838
839 std::string result;
840 CHECK(android::base::ReadFdToString(out.get(), &result));
841 EXPECT_EQ(result, "hello");
842}
843
844TEST_P(BinderRpc, SendFiles) {
845 auto proc = createRpcTestSocketServerProcess({
846 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
847 .serverSupportedFileDescriptorTransportModes =
848 {RpcSession::FileDescriptorTransportMode::UNIX},
849 });
850
851 std::vector<android::os::ParcelFileDescriptor> files;
852 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
853 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
854 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
855 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
856
857 android::os::ParcelFileDescriptor out;
858 auto status = proc.rootIface->concatFiles(files, &out);
859 if (!supportsFdTransport()) {
860 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
861 return;
862 }
863 ASSERT_TRUE(status.isOk()) << status;
864
865 std::string result;
866 CHECK(android::base::ReadFdToString(out.get(), &result));
867 EXPECT_EQ(result, "123abcd");
868}
869
870TEST_P(BinderRpc, SendMaxFiles) {
871 if (!supportsFdTransport()) {
872 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
873 }
874
875 auto proc = createRpcTestSocketServerProcess({
876 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
877 .serverSupportedFileDescriptorTransportModes =
878 {RpcSession::FileDescriptorTransportMode::UNIX},
879 });
880
881 std::vector<android::os::ParcelFileDescriptor> files;
882 for (int i = 0; i < 253; i++) {
883 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
884 }
885
886 android::os::ParcelFileDescriptor out;
887 auto status = proc.rootIface->concatFiles(files, &out);
888 ASSERT_TRUE(status.isOk()) << status;
889
890 std::string result;
891 CHECK(android::base::ReadFdToString(out.get(), &result));
892 EXPECT_EQ(result, std::string(253, 'a'));
893}
894
895TEST_P(BinderRpc, SendTooManyFiles) {
896 if (!supportsFdTransport()) {
897 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
898 }
899
900 auto proc = createRpcTestSocketServerProcess({
901 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
902 .serverSupportedFileDescriptorTransportModes =
903 {RpcSession::FileDescriptorTransportMode::UNIX},
904 });
905
906 std::vector<android::os::ParcelFileDescriptor> files;
907 for (int i = 0; i < 254; i++) {
908 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
909 }
910
911 android::os::ParcelFileDescriptor out;
912 auto status = proc.rootIface->concatFiles(files, &out);
913 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
914}
915
Andrei Homescufc221502022-10-08 03:51:17 +0000916TEST_P(BinderRpc, AppendInvalidFd) {
917 auto proc = createRpcTestSocketServerProcess({
918 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
919 .serverSupportedFileDescriptorTransportModes =
920 {RpcSession::FileDescriptorTransportMode::UNIX},
921 });
922
923 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
924 ASSERT_NE(badFd, -1);
925
926 // Close the file descriptor so it becomes invalid for dup
927 close(badFd);
928
929 Parcel p1;
930 p1.markForBinder(proc.rootBinder);
931 p1.writeInt32(3);
932 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
933
934 Parcel pRaw;
935 pRaw.markForBinder(proc.rootBinder);
936 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
937
938 pRaw.setDataPosition(0);
939 EXPECT_EQ(3, pRaw.readInt32());
940 ASSERT_EQ(-1, pRaw.readFileDescriptor());
941}
942
Steven Moreland37aff182021-03-26 02:04:16 +0000943TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000944 if constexpr (!kEnableSharedLibs) {
945 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
946 }
947
Steven Moreland4313d7e2021-07-15 23:41:22 +0000948 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000949
950 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
951 ASSERT_NE(binder, nullptr);
952
953 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
954}
955
956TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000957 if constexpr (!kEnableSharedLibs) {
958 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
959 }
960
Steven Moreland4313d7e2021-07-15 23:41:22 +0000961 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000962
963 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
964 ASSERT_NE(binder, nullptr);
965
966 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
967 ASSERT_NE(ndkBinder, nullptr);
968
969 std::string out;
970 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
971 ASSERT_TRUE(status.isOk()) << status.getDescription();
972 ASSERT_EQ("aoeuaoeu", out);
973}
974
Steven Moreland5553ac42020-11-11 02:14:45 +0000975ssize_t countFds() {
976 DIR* dir = opendir("/proc/self/fd/");
977 if (dir == nullptr) return -1;
978 ssize_t ret = 0;
979 dirent* ent;
980 while ((ent = readdir(dir)) != nullptr) ret++;
981 closedir(dir);
982 return ret;
983}
984
Andrei Homescua858b0e2022-08-01 23:43:09 +0000985TEST_P(BinderRpc, Fds) {
986 if (serverSingleThreaded()) {
987 GTEST_SKIP() << "This test requires multiple threads";
988 }
989
Steven Moreland5553ac42020-11-11 02:14:45 +0000990 ssize_t beforeFds = countFds();
991 ASSERT_GE(beforeFds, 0);
992 {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000993 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +0000994 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
995 }
996 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
997}
998
Steven Morelandda573042021-06-12 01:13:45 +0000999static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001000 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001001 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001002
Andrei Homescu992a4052022-06-28 21:26:18 +00001003 android::base::unique_fd serverFd(
1004 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1005 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1006
1007 sockaddr_vm serverAddr{
1008 .svm_family = AF_VSOCK,
1009 .svm_port = vsockPort,
1010 .svm_cid = VMADDR_CID_ANY,
1011 };
1012 int ret = TEMP_FAILURE_RETRY(
1013 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1014 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1015 strerror(errno));
1016
1017 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1018 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1019 strerror(errno));
1020
1021 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1022 // to see if the kernel supports it. It's safe to use a blocking
1023 // connect because vsock sockets have a 2 second connection timeout,
1024 // and they return ETIMEDOUT after that.
1025 android::base::unique_fd connectFd(
1026 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1027 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1028 strerror(errno));
1029
1030 bool success = false;
1031 sockaddr_vm connectAddr{
1032 .svm_family = AF_VSOCK,
1033 .svm_port = vsockPort,
1034 .svm_cid = VMADDR_CID_LOCAL,
1035 };
1036 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1037 sizeof(connectAddr)));
1038 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1039 android::base::unique_fd acceptFd;
1040 while (true) {
1041 pollfd pfd[]{
1042 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1043 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1044 };
1045 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1046 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1047
1048 if (pfd[0].revents & POLLIN) {
1049 sockaddr_vm acceptAddr;
1050 socklen_t acceptAddrLen = sizeof(acceptAddr);
1051 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1052 reinterpret_cast<sockaddr*>(&acceptAddr),
1053 &acceptAddrLen, SOCK_CLOEXEC));
1054 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1055 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1056 "Truncated address");
1057
1058 // Store the fd in acceptFd so we keep the connection alive
1059 // while polling connectFd
1060 acceptFd.reset(ret);
1061 }
1062
1063 if (pfd[1].revents & POLLOUT) {
1064 // Connect either succeeded or timed out
1065 int connectErrno;
1066 socklen_t connectErrnoLen = sizeof(connectErrno);
1067 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1068 &connectErrnoLen);
1069 LOG_ALWAYS_FATAL_IF(ret == -1,
1070 "Could not getsockopt() after connect() "
1071 "on non-blocking socket: %s.",
1072 strerror(errno));
1073
1074 // We're done, this is all we wanted
1075 success = connectErrno == 0;
1076 break;
1077 }
1078 }
1079 } else {
1080 success = ret == 0;
1081 }
1082
1083 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1084
1085 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001086}
1087
Yifan Hong1deca4b2021-09-10 16:16:44 -07001088static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001089 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1090 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001091
1092 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001093
1094 static bool hasVsockLoopback = testSupportVsockLoopback();
1095
1096 if (hasVsockLoopback) {
1097 ret.push_back(SocketType::VSOCK);
1098 }
1099
1100 return ret;
1101}
1102
Yifan Hong702115c2021-06-24 15:39:18 -07001103INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1104 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001105 ::testing::ValuesIn(RpcSecurityValues()),
1106 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001107 ::testing::ValuesIn(testVersions()),
1108 ::testing::Values(false, true),
1109 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001110 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001111
Yifan Hong702115c2021-06-24 15:39:18 -07001112class BinderRpcServerRootObject
1113 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001114
1115TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1116 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1117 auto setRootObject = [](bool isStrong) -> SetFn {
1118 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1119 };
1120
Yifan Hong702115c2021-06-24 15:39:18 -07001121 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1122 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001123 auto binder1 = sp<BBinder>::make();
1124 IBinder* binderRaw1 = binder1.get();
1125 setRootObject(isStrong1)(server.get(), binder1);
1126 EXPECT_EQ(binderRaw1, server->getRootObject());
1127 binder1.clear();
1128 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1129
1130 auto binder2 = sp<BBinder>::make();
1131 IBinder* binderRaw2 = binder2.get();
1132 setRootObject(isStrong2)(server.get(), binder2);
1133 EXPECT_EQ(binderRaw2, server->getRootObject());
1134 binder2.clear();
1135 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1136}
1137
1138INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001139 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1140 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001141
Yifan Hong1a235852021-05-13 16:07:47 -07001142class OneOffSignal {
1143public:
1144 // If notify() was previously called, or is called within |duration|, return true; else false.
1145 template <typename R, typename P>
1146 bool wait(std::chrono::duration<R, P> duration) {
1147 std::unique_lock<std::mutex> lock(mMutex);
1148 return mCv.wait_for(lock, duration, [this] { return mValue; });
1149 }
1150 void notify() {
1151 std::unique_lock<std::mutex> lock(mMutex);
1152 mValue = true;
1153 lock.unlock();
1154 mCv.notify_all();
1155 }
1156
1157private:
1158 std::mutex mMutex;
1159 std::condition_variable mCv;
1160 bool mValue = false;
1161};
1162
Yifan Hong194acf22021-06-29 18:44:56 -07001163TEST(BinderRpc, Java) {
1164#if !defined(__ANDROID__)
1165 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1166 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1167 "to binderHostDeviceTest. Hence, just disable this test on host.";
1168#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001169 if constexpr (!kEnableKernelIpc) {
1170 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1171 "at build time.";
1172 }
1173
Yifan Hong194acf22021-06-29 18:44:56 -07001174 sp<IServiceManager> sm = defaultServiceManager();
1175 ASSERT_NE(nullptr, sm);
1176 // Any Java service with non-empty getInterfaceDescriptor() would do.
1177 // Let's pick batteryproperties.
1178 auto binder = sm->checkService(String16("batteryproperties"));
1179 ASSERT_NE(nullptr, binder);
1180 auto descriptor = binder->getInterfaceDescriptor();
1181 ASSERT_GE(descriptor.size(), 0);
1182 ASSERT_EQ(OK, binder->pingBinder());
1183
1184 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001185 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001186 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001187 auto socket = rpcServer->releaseServer();
1188
1189 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001190 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1191
Yifan Honge3caaf22022-01-12 14:46:56 -08001192 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1193 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001194 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001195 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1196 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001197 << statusToString(setRpcClientDebugStatus);
1198 GTEST_SKIP();
1199 }
1200
1201 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001202
1203 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001204 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001205 auto rpcBinder = rpcSession->getRootObject();
1206 ASSERT_NE(nullptr, rpcBinder);
1207
1208 ASSERT_EQ(OK, rpcBinder->pingBinder());
1209
1210 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1211 << "getInterfaceDescriptor should not crash system_server";
1212 ASSERT_EQ(OK, rpcBinder->pingBinder());
1213}
1214
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001215class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1216public:
1217 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1218 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1219 std::to_string(std::get<1>(info.param));
1220 }
1221};
1222
1223TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1224 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1225 int sinkFd = sink.get();
1226 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1227 server->setProtocolVersion(std::get<1>(GetParam()));
1228 ASSERT_FALSE(server->hasServer());
1229 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1230 ASSERT_TRUE(server->hasServer());
1231 base::unique_fd retrieved = server->releaseServer();
1232 ASSERT_FALSE(server->hasServer());
1233 ASSERT_EQ(sinkFd, retrieved.get());
1234}
1235
1236TEST_P(BinderRpcServerOnly, Shutdown) {
1237 if constexpr (!kEnableRpcThreads) {
1238 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1239 }
1240
1241 auto addr = allocateSocketAddress();
1242 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1243 server->setProtocolVersion(std::get<1>(GetParam()));
1244 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1245 auto joinEnds = std::make_shared<OneOffSignal>();
1246
1247 // If things are broken and the thread never stops, don't block other tests. Because the thread
1248 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1249 // shared pointers are passed.
1250 std::thread([server, joinEnds] {
1251 server->join();
1252 joinEnds->notify();
1253 }).detach();
1254
1255 bool shutdown = false;
1256 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001257 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001258 if (server->shutdown()) shutdown = true;
1259 }
1260 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1261
1262 ASSERT_TRUE(joinEnds->wait(2s))
1263 << "After server->shutdown() returns true, join() did not stop after 2s";
1264}
1265
Frederick Mayledc07cf82022-05-26 20:30:12 +00001266INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1267 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1268 ::testing::ValuesIn(testVersions())),
1269 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001270
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001271class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001272public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001273 // Only parameterized only server version because `RpcSession` is bypassed
1274 // in the client half of the tests.
1275 using Param =
1276 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001277 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001278
1279 // A server that handles client socket connections.
1280 class Server {
1281 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001282 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1283
Yifan Hong1deca4b2021-09-10 16:16:44 -07001284 explicit Server() {}
1285 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001286 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001287 [[nodiscard]] AssertionResult setUp(
1288 const Param& param,
1289 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001290 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001291 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001292 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001293 switch (socketType) {
1294 case SocketType::PRECONNECTED: {
1295 return AssertionFailure() << "Not supported by this test";
1296 } break;
1297 case SocketType::UNIX: {
1298 auto addr = allocateSocketAddress();
1299 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1300 if (status != OK) {
1301 return AssertionFailure()
1302 << "setupUnixDomainServer: " << statusToString(status);
1303 }
1304 mConnectToServer = [addr] {
1305 return connectTo(UnixSocketAddress(addr.c_str()));
1306 };
1307 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001308 case SocketType::UNIX_BOOTSTRAP: {
1309 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1310 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1311 return AssertionFailure() << "Socketpair() failed";
1312 }
1313 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1314 std::move(bootstrapFdServer));
1315 if (status != OK) {
1316 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1317 << statusToString(status);
1318 }
1319 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1320 mAcceptConnection = &Server::recvmsgServerConnection;
1321 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1322 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001323 case SocketType::UNIX_RAW: {
1324 auto addr = allocateSocketAddress();
1325 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1326 if (status != OK) {
1327 return AssertionFailure()
1328 << "setupRawSocketServer: " << statusToString(status);
1329 }
1330 mConnectToServer = [addr] {
1331 return connectTo(UnixSocketAddress(addr.c_str()));
1332 };
1333 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001334 case SocketType::VSOCK: {
1335 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001336 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001337 if (status != OK) {
1338 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1339 }
1340 mConnectToServer = [port] {
1341 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1342 };
1343 } break;
1344 case SocketType::INET: {
1345 unsigned int port;
1346 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1347 if (status != OK) {
1348 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1349 }
1350 mConnectToServer = [port] {
1351 const char* addr = kLocalInetAddress;
1352 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1353 if (aiStart == nullptr) return base::unique_fd{};
1354 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1355 auto fd = connectTo(
1356 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1357 if (fd.ok()) return fd;
1358 }
1359 ALOGE("None of the socket address resolved for %s:%u can be connected",
1360 addr, port);
1361 return base::unique_fd{};
1362 };
1363 }
1364 }
1365 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001366 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001367 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001368 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1369 mSetup = true;
1370 return AssertionSuccess();
1371 }
1372 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1373 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1374 return mCertVerifier;
1375 }
1376 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1377 void start() {
1378 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1379 mThread = std::make_unique<std::thread>(&Server::run, this);
1380 }
David Brazdil21c887c2022-09-23 12:25:18 +01001381
1382 base::unique_fd acceptServerConnection() {
1383 return base::unique_fd(TEMP_FAILURE_RETRY(
1384 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1385 }
1386
1387 base::unique_fd recvmsgServerConnection() {
1388 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1389 int buf;
1390 iovec iov{&buf, sizeof(buf)};
1391
1392 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1393 int savedErrno = errno;
1394 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1395 }
1396 if (fds.size() != 1) {
1397 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1398 }
1399 return std::move(std::get<base::unique_fd>(fds[0]));
1400 }
1401
Yifan Hong1deca4b2021-09-10 16:16:44 -07001402 void run() {
1403 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1404
1405 std::vector<std::thread> threads;
1406 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001407 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001408 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1409 }
1410
1411 for (auto& thread : threads) thread.join();
1412 }
1413 void handleOne(android::base::unique_fd acceptedFd) {
1414 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001415 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001416 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001417 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001418 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001419 }
Yifan Honge07d2732021-09-13 21:59:14 -07001420 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001421 shutdown();
1422 join();
1423 }
1424 void shutdown() { mFdTrigger->trigger(); }
1425
1426 void setPostConnect(
1427 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1428 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001429 }
1430
1431 private:
1432 std::unique_ptr<std::thread> mThread;
1433 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001434 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001435 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001436 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001437 std::unique_ptr<RpcTransportCtx> mCtx;
1438 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1439 std::make_shared<RpcCertificateVerifierSimple>();
1440 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001441 // The function invoked after connection and handshake. By default, it is
1442 // |defaultPostConnect| that sends |kMessage| to the client.
1443 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1444 Server::defaultPostConnect;
1445
1446 void join() {
1447 if (mThread != nullptr) {
1448 mThread->join();
1449 mThread = nullptr;
1450 }
1451 }
1452
1453 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1454 FdTrigger* fdTrigger) {
1455 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001456 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001457 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001458 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001459 if (status != OK) return AssertionFailure() << statusToString(status);
1460 return AssertionSuccess();
1461 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001462 };
1463
1464 class Client {
1465 public:
1466 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1467 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001468 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001469 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1470 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001471 mFdTrigger = FdTrigger::make();
1472 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1473 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1474 return AssertionSuccess();
1475 }
1476 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1477 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1478 return mCertVerifier;
1479 }
Yifan Hong67519322021-09-13 18:51:16 -07001480 // connect() and do handshake
1481 bool setUpTransport() {
1482 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001483 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001484 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1485 return mClientTransport != nullptr;
1486 }
1487 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1488 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1489 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001490 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001491 status_t readStatus =
1492 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001493 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001494 if (readStatus != OK) {
1495 return AssertionFailure() << statusToString(readStatus);
1496 }
1497 if (readMessage != expectedMessage) {
1498 return AssertionFailure()
1499 << "Expected " << expectedMessage << ", actual " << readMessage;
1500 }
1501 return AssertionSuccess();
1502 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001503 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001504 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001505 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1506 return;
1507 }
1508 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001509 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001510 }
1511
Pawan49d74cb2022-08-03 21:19:11 +00001512 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1513
Yifan Hong1deca4b2021-09-10 16:16:44 -07001514 private:
1515 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001516 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001517 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1518 std::unique_ptr<RpcTransportCtx> mCtx;
1519 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1520 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001521 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001522 };
1523
1524 // Make A trust B.
1525 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001526 static status_t trust(RpcSecurity rpcSecurity,
1527 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1528 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001529 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001530 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1531 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1532 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001533 }
1534
1535 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001536};
1537
1538class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1539public:
1540 using Server = RpcTransportTestUtils::Server;
1541 using Client = RpcTransportTestUtils::Client;
1542 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001543 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001544 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1545 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001546 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001547 return ret;
1548 }
1549 static std::vector<ParamType> getRpcTranportTestParams() {
1550 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001551 for (auto serverVersion : testVersions()) {
1552 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1553 for (auto rpcSecurity : RpcSecurityValues()) {
1554 switch (rpcSecurity) {
1555 case RpcSecurity::RAW: {
1556 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1557 } break;
1558 case RpcSecurity::TLS: {
1559 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1560 serverVersion);
1561 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1562 serverVersion);
1563 } break;
1564 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001565 }
1566 }
1567 }
1568 return ret;
1569 }
1570 template <typename A, typename B>
1571 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001572 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1573 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001574 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1575 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001576 void SetUp() override {
1577 if constexpr (!kEnableRpcThreads) {
1578 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1579 }
1580 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001581};
1582
1583TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001584 auto server = std::make_unique<Server>();
1585 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001586
1587 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001588 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001589
1590 ASSERT_EQ(OK, trust(&client, server));
1591 ASSERT_EQ(OK, trust(server, &client));
1592
1593 server->start();
1594 client.run();
1595}
1596
1597TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001598 auto server = std::make_unique<Server>();
1599 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001600
1601 std::vector<Client> clients;
1602 for (int i = 0; i < 2; i++) {
1603 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001604 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001605 ASSERT_EQ(OK, trust(&client, server));
1606 ASSERT_EQ(OK, trust(server, &client));
1607 }
1608
1609 server->start();
1610 for (auto& client : clients) client.run();
1611}
1612
1613TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001614 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1615 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001616
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001617 auto untrustedServer = std::make_unique<Server>();
1618 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619
1620 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001621 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001622
1623 ASSERT_EQ(OK, trust(untrustedServer, &client));
1624
1625 untrustedServer->start();
1626
1627 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1628 // the client can't verify the server's identity.
1629 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1630 client.run(handshakeOk);
1631}
1632TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001633 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1634 (void)serverVersion;
1635
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001636 auto validServer = std::make_unique<Server>();
1637 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001638
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001639 auto maliciousServer = std::make_unique<Server>();
1640 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001641
1642 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001643 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001644
1645 ASSERT_EQ(OK, trust(&client, validServer));
1646 ASSERT_EQ(OK, trust(validServer, &client));
1647 ASSERT_EQ(OK, trust(maliciousServer, &client));
1648
1649 maliciousServer->start();
1650
1651 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1652 // the client can't verify the server's identity.
1653 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1654 client.run(handshakeOk);
1655}
1656
1657TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001658 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1659 (void)serverVersion;
1660
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001661 auto server = std::make_unique<Server>();
1662 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001663
1664 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001665 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001666
1667 ASSERT_EQ(OK, trust(&client, server));
1668
1669 server->start();
1670
1671 // For TLS, Client should be able to verify server's identity, so client should see
1672 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1673 // identity and should drop the connection, so client shouldn't be able to read anything.
1674 bool readOk = rpcSecurity != RpcSecurity::TLS;
1675 client.run(true, readOk);
1676}
1677
1678TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001679 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1680 (void)serverVersion;
1681
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001682 auto server = std::make_unique<Server>();
1683 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001684
1685 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001686 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001687 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001688 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001689
1690 ASSERT_EQ(OK, trust(&validClient, server));
1691 ASSERT_EQ(OK, trust(&maliciousClient, server));
1692
1693 server->start();
1694
1695 // See UntrustedClient.
1696 bool readOk = rpcSecurity != RpcSecurity::TLS;
1697 maliciousClient.run(true, readOk);
1698}
1699
Yifan Hong67519322021-09-13 18:51:16 -07001700TEST_P(RpcTransportTest, Trigger) {
1701 std::string msg2 = ", world!";
1702 std::mutex writeMutex;
1703 std::condition_variable writeCv;
1704 bool shouldContinueWriting = false;
1705 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001706 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001707 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001708 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1709 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001710 if (status != OK) return AssertionFailure() << statusToString(status);
1711
1712 {
1713 std::unique_lock<std::mutex> lock(writeMutex);
1714 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1715 return AssertionFailure() << "write barrier not cleared in time!";
1716 }
1717 }
1718
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001719 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001720 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1721 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001722 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001723 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001724 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001725 << statusToString(status);
1726 return AssertionSuccess();
1727 };
1728
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001729 auto server = std::make_unique<Server>();
1730 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001731
1732 // Set up client
1733 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001734 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001735
1736 // Exchange keys
1737 ASSERT_EQ(OK, trust(&client, server));
1738 ASSERT_EQ(OK, trust(server, &client));
1739
1740 server->setPostConnect(serverPostConnect);
1741
Yifan Hong67519322021-09-13 18:51:16 -07001742 server->start();
1743 // connect() to server and do handshake
1744 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001745 // read the first message. This ensures that server has finished handshake and start handling
1746 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001747 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001748 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1749 // write is on an FdTrigger that has been shut down.
1750 server->shutdown();
1751 // Continues server thread to write the second message.
1752 {
Yifan Hong22211f82021-09-14 12:32:25 -07001753 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001754 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001755 }
Yifan Hong22211f82021-09-14 12:32:25 -07001756 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001757 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001758 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001759 // On the client side, second read fails with DEAD_OBJECT
1760 ASSERT_FALSE(client.readMessage(msg2));
1761}
1762
Pawan49d74cb2022-08-03 21:19:11 +00001763TEST_P(RpcTransportTest, CheckWaitingForRead) {
1764 std::mutex readMutex;
1765 std::condition_variable readCv;
1766 bool shouldContinueReading = false;
1767 // Server will write data on transport once its started
1768 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1769 std::string message(RpcTransportTestUtils::kMessage);
1770 iovec messageIov{message.data(), message.size()};
1771 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1772 std::nullopt, nullptr);
1773 if (status != OK) return AssertionFailure() << statusToString(status);
1774
1775 {
1776 std::unique_lock<std::mutex> lock(readMutex);
1777 shouldContinueReading = true;
1778 lock.unlock();
1779 readCv.notify_all();
1780 }
1781 return AssertionSuccess();
1782 };
1783
1784 // Setup Server and client
1785 auto server = std::make_unique<Server>();
1786 ASSERT_TRUE(server->setUp(GetParam()));
1787
1788 Client client(server->getConnectToServerFn());
1789 ASSERT_TRUE(client.setUp(GetParam()));
1790
1791 ASSERT_EQ(OK, trust(&client, server));
1792 ASSERT_EQ(OK, trust(server, &client));
1793 server->setPostConnect(serverPostConnect);
1794
1795 server->start();
1796 ASSERT_TRUE(client.setUpTransport());
1797 {
1798 // Wait till server writes data
1799 std::unique_lock<std::mutex> lock(readMutex);
1800 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1801 }
1802
1803 // Since there is no read polling here, we will get polling count 0
1804 ASSERT_FALSE(client.isTransportWaiting());
1805 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1806 // Thread should increment polling count, read and decrement polling count
1807 // Again, polling count should be zero here
1808 ASSERT_FALSE(client.isTransportWaiting());
1809
1810 server->shutdown();
1811}
1812
Yifan Hong1deca4b2021-09-10 16:16:44 -07001813INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001814 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001815 RpcTransportTest::PrintParamInfo);
1816
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001817class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001818 : public testing::TestWithParam<
1819 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001820public:
1821 template <typename A, typename B>
1822 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001823 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1824 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001825 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1826 }
1827 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001828 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1829 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1830 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001831 };
1832};
1833
1834TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001835 if constexpr (!kEnableRpcThreads) {
1836 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1837 }
1838
Frederick Mayledc07cf82022-05-26 20:30:12 +00001839 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001840
1841 std::vector<uint8_t> pkeyData, certData;
1842 {
1843 auto pkey = makeKeyPairForSelfSignedCert();
1844 ASSERT_NE(nullptr, pkey);
1845 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1846 ASSERT_NE(nullptr, cert);
1847 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1848 certData = serializeCertificate(cert.get(), certificateFormat);
1849 }
1850
1851 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1852 auto desCert = deserializeCertificate(certData, certificateFormat);
1853 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001854 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1855 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001856
1857 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1858 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1859
1860 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1861 ASSERT_TRUE(client.setUp(utilsParam));
1862
1863 ASSERT_EQ(OK, trust(&client, server));
1864 ASSERT_EQ(OK, trust(server, &client));
1865
1866 server->start();
1867 client.run();
1868}
1869
1870INSTANTIATE_TEST_CASE_P(
1871 BinderRpc, RpcTransportTlsKeyTest,
1872 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1873 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001874 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1875 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001876 RpcTransportTlsKeyTest::PrintParamInfo);
1877
Steven Morelandc1635952021-04-01 16:20:47 +00001878} // namespace android
1879
1880int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001881 ::testing::InitGoogleTest(&argc, argv);
1882 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001883
Steven Moreland5553ac42020-11-11 02:14:45 +00001884 return RUN_ALL_TESTS();
1885}