blob: 739c2171f3234e871d792b6bea4c43760f9acac5 [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
Frederick Maylea12b0962022-06-25 01:13:22 +000017#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018
Steven Morelandc1635952021-04-01 16:20:47 +000019#include <chrono>
20#include <cstdlib>
21#include <iostream>
22#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000023#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000024
Andrei Homescu2a298012022-06-15 01:08:54 +000025#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070026#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000027#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000028#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000029
Andrei Homescu2a298012022-06-15 01:08:54 +000030#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000031#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Yifan Hong1a235852021-05-13 16:07:47 -070033using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070034using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070035using testing::AssertionFailure;
36using testing::AssertionResult;
37using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070038
Steven Moreland5553ac42020-11-11 02:14:45 +000039namespace android {
40
Andrei Homescu12106de2022-04-27 04:42:21 +000041#ifdef BINDER_TEST_NO_SHARED_LIBS
42constexpr bool kEnableSharedLibs = false;
43#else
44constexpr bool kEnableSharedLibs = true;
45#endif
46
Frederick Maylea12b0962022-06-25 01:13:22 +000047static std::string WaitStatusToString(int wstatus) {
48 if (WIFEXITED(wstatus)) {
49 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
50 }
51 if (WIFSIGNALED(wstatus)) {
52 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
53 }
54 return base::StringPrintf("unexpected state %d", wstatus);
55}
56
Steven Moreland276d8df2022-09-28 23:56:39 +000057static void debugBacktrace(pid_t pid) {
58 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
59 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
60}
61
Steven Moreland5553ac42020-11-11 02:14:45 +000062class Process {
63public:
Andrei Homescu96834632022-10-14 00:49:49 +000064 Process(Process&& other)
65 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
66 mReadEnd(std::move(other.mReadEnd)),
67 mWriteEnd(std::move(other.mWriteEnd)) {
68 // The default move constructor doesn't clear mPid after moving it,
69 // which we need to do because the destructor checks for mPid!=0
70 mPid = other.mPid;
71 other.mPid = 0;
72 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070073 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
74 android::base::borrowed_fd /* readEnd */)>& f) {
75 android::base::unique_fd childWriteEnd;
76 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000077 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
78 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000079 if (0 == (mPid = fork())) {
80 // racey: assume parent doesn't crash before this is set
81 prctl(PR_SET_PDEATHSIG, SIGHUP);
82
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000084
85 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000086 }
87 }
88 ~Process() {
89 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +000090 int wstatus;
91 waitpid(mPid, &wstatus, 0);
92 if (mCustomExitStatusCheck) {
93 mCustomExitStatusCheck(wstatus);
94 } else {
95 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
96 << "server process failed: " << WaitStatusToString(wstatus);
97 }
Steven Moreland5553ac42020-11-11 02:14:45 +000098 }
99 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700100 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700101 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000102
Frederick Maylea12b0962022-06-25 01:13:22 +0000103 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
104 mCustomExitStatusCheck = std::move(f);
105 }
106
Frederick Mayle69a0c992022-05-26 20:38:39 +0000107 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
108 void terminate() { kill(mPid, SIGTERM); }
109
Steven Moreland276d8df2022-09-28 23:56:39 +0000110 pid_t getPid() { return mPid; }
111
Steven Moreland5553ac42020-11-11 02:14:45 +0000112private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000114 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700115 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700116 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000117};
118
119static std::string allocateSocketAddress() {
120 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000121 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700122 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
123 unlink(ret.c_str());
124 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000125};
126
Steven Morelandda573042021-06-12 01:13:45 +0000127static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000128 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000129 return vsockPort++;
130}
131
Alice Wang893a9912022-10-24 10:44:09 +0000132static base::unique_fd initUnixSocket(std::string addr) {
133 auto socket_addr = UnixSocketAddress(addr.c_str());
134 base::unique_fd fd(
135 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
136 CHECK(fd.ok());
137 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
138 return fd;
139}
140
Andrei Homescu96834632022-10-14 00:49:49 +0000141// Destructors need to be defined, even if pure virtual
142ProcessSession::~ProcessSession() {}
143
144class LinuxProcessSession : public ProcessSession {
145public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000146 // reference to process hosting a socket server
147 Process host;
148
Andrei Homescu96834632022-10-14 00:49:49 +0000149 LinuxProcessSession(LinuxProcessSession&&) = default;
150 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
151 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000152 for (auto& session : sessions) {
153 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000154 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000155
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000156 for (auto& info : sessions) {
157 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000158
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159 EXPECT_NE(nullptr, session);
160 EXPECT_NE(nullptr, session->state());
161 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000162
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000163 wp<RpcSession> weakSession = session;
164 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000165
Steven Moreland57042712022-10-04 23:56:45 +0000166 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
167 // the object should not actually be promotable. By looping, we distinguish a race here
168 // from a bug causing the object to not be promotable.
169 for (size_t i = 0; i < 3; i++) {
170 sp<RpcSession> strongSession = weakSession.promote();
171 EXPECT_EQ(nullptr, strongSession)
172 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
173 "Leaked sess: ")
174 << strongSession->getStrongCount() << " checked time " << i;
175
176 if (strongSession != nullptr) {
177 sleep(1);
178 }
179 }
Steven Moreland736664b2021-05-01 04:27:25 +0000180 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000181 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000182
Andrei Homescu96834632022-10-14 00:49:49 +0000183 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
184 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000185 }
Andrei Homescu96834632022-10-14 00:49:49 +0000186
187 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000188};
189
Yifan Hong1deca4b2021-09-10 16:16:44 -0700190static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700191 base::unique_fd serverFd(
192 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
193 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700194 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
195 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700196
197 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
198 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700199 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
200 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700201 }
202 return serverFd;
203}
204
David Brazdil21c887c2022-09-23 12:25:18 +0100205static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
206 base::unique_fd sockClient, sockServer;
207 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
208 int savedErrno = errno;
209 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
210 }
211
212 int zero = 0;
213 iovec iov{&zero, sizeof(zero)};
214 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
215 fds.emplace_back(std::move(sockServer));
216
217 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
218 int savedErrno = errno;
219 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
220 }
221 return std::move(sockClient);
222}
223
Andrei Homescu96834632022-10-14 00:49:49 +0000224std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
225 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
226 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
227 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
228 if (singleThreaded) {
229 ret += "_single_threaded";
230 }
231 if (noKernel) {
232 ret += "_no_kernel";
233 }
234 return ret;
235}
Andrei Homescu2a298012022-06-15 01:08:54 +0000236
Andrei Homescu96834632022-10-14 00:49:49 +0000237// This creates a new process serving an interface on a certain number of
238// threads.
239std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
240 const BinderRpcOptions& options) {
241 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000242
Andrei Homescu96834632022-10-14 00:49:49 +0000243 SocketType socketType = std::get<0>(GetParam());
244 RpcSecurity rpcSecurity = std::get<1>(GetParam());
245 uint32_t clientVersion = std::get<2>(GetParam());
246 uint32_t serverVersion = std::get<3>(GetParam());
247 bool singleThreaded = std::get<4>(GetParam());
248 bool noKernel = std::get<5>(GetParam());
249
250 std::string path = android::base::GetExecutableDirectory();
251 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
252 singleThreaded ? "_single_threaded" : "",
253 noKernel ? "_no_kernel" : "");
254
Alice Wang1ef010b2022-11-14 09:09:25 +0000255 base::unique_fd bootstrapClientFd, socketFd;
256
Alice Wang893a9912022-10-24 10:44:09 +0000257 auto addr = allocateSocketAddress();
258 // Initializes the socket before the fork/exec.
259 if (socketType == SocketType::UNIX_RAW) {
260 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000261 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
262 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
263 // This is because we cannot pass ParcelFileDescriptor over a pipe.
264 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
265 int savedErrno = errno;
266 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
267 }
Alice Wang893a9912022-10-24 10:44:09 +0000268 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000269
Andrei Homescu96834632022-10-14 00:49:49 +0000270 auto ret = std::make_unique<LinuxProcessSession>(
271 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
272 auto writeFd = std::to_string(writeEnd.get());
273 auto readFd = std::to_string(readEnd.get());
274 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
275 NULL);
276 }));
277
278 BinderRpcTestServerConfig serverConfig;
279 serverConfig.numThreads = options.numThreads;
280 serverConfig.socketType = static_cast<int32_t>(socketType);
281 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
282 serverConfig.serverVersion = serverVersion;
283 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000284 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000285 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000286 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
287 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
288 static_cast<int32_t>(mode));
289 }
290 writeToFd(ret->host.writeEnd(), serverConfig);
291
292 std::vector<sp<RpcSession>> sessions;
293 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
294 for (size_t i = 0; i < options.numSessions; i++) {
295 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
David Brazdil21c887c2022-09-23 12:25:18 +0100296 }
297
Andrei Homescu96834632022-10-14 00:49:49 +0000298 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
299 BinderRpcTestClientInfo clientInfo;
300 for (const auto& session : sessions) {
301 auto& parcelableCert = clientInfo.certs.emplace_back();
302 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
303 }
304 writeToFd(ret->host.writeEnd(), clientInfo);
305
306 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
307 if (socketType == SocketType::INET) {
308 CHECK_NE(0, serverInfo.port);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000309 }
310
Andrei Homescu96834632022-10-14 00:49:49 +0000311 if (rpcSecurity == RpcSecurity::TLS) {
312 const auto& serverCert = serverInfo.cert.data;
313 CHECK_EQ(OK,
314 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700315 }
316
Andrei Homescu96834632022-10-14 00:49:49 +0000317 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000318
Andrei Homescu96834632022-10-14 00:49:49 +0000319 for (const auto& session : sessions) {
320 CHECK(session->setProtocolVersion(clientVersion));
321 session->setMaxIncomingThreads(options.numIncomingConnections);
322 session->setMaxOutgoingThreads(options.numOutgoingConnections);
323 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000324
Andrei Homescu96834632022-10-14 00:49:49 +0000325 switch (socketType) {
326 case SocketType::PRECONNECTED:
327 status = session->setupPreconnectedClient({}, [=]() {
328 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
329 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000330 break;
Alice Wang893a9912022-10-24 10:44:09 +0000331 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000332 case SocketType::UNIX:
333 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
334 break;
335 case SocketType::UNIX_BOOTSTRAP:
336 status = session->setupUnixDomainSocketBootstrapClient(
337 base::unique_fd(dup(bootstrapClientFd.get())));
338 break;
339 case SocketType::VSOCK:
340 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
341 break;
342 case SocketType::INET:
343 status = session->setupInetClient("127.0.0.1", serverInfo.port);
344 break;
345 default:
346 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000347 }
Andrei Homescu96834632022-10-14 00:49:49 +0000348 if (options.allowConnectFailure && status != OK) {
349 ret->sessions.clear();
350 break;
351 }
352 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
353 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000354 }
Andrei Homescu96834632022-10-14 00:49:49 +0000355 return ret;
356}
Steven Morelandc1635952021-04-01 16:20:47 +0000357
Andrei Homescua858b0e2022-08-01 23:43:09 +0000358TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
359 if (clientOrServerSingleThreaded()) {
360 GTEST_SKIP() << "This test requires multiple threads";
361 }
362
Steven Moreland5553ac42020-11-11 02:14:45 +0000363 constexpr size_t kNumThreads = 10;
364
Steven Moreland4313d7e2021-07-15 23:41:22 +0000365 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000366
367 EXPECT_OK(proc.rootIface->lock());
368
369 // block all but one thread taking locks
370 std::vector<std::thread> ts;
371 for (size_t i = 0; i < kNumThreads - 1; i++) {
372 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
373 }
374
Steven Morelanddd231e22022-09-08 19:47:49 +0000375 usleep(10000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000376
377 // other calls still work
378 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
379
Steven Morelanddd231e22022-09-08 19:47:49 +0000380 constexpr size_t blockTimeMs = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000381 size_t epochMsBefore = epochMillis();
382 // after this, we should never see a response within this time
383 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
384
385 // this call should be blocked for blockTimeMs
386 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
387
388 size_t epochMsAfter = epochMillis();
389 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
390
391 for (auto& t : ts) t.join();
392}
393
Andrei Homescu96834632022-10-14 00:49:49 +0000394static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
395 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000396 size_t epochMsBefore = epochMillis();
397
398 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700399 for (size_t i = 0; i < numCalls; i++) {
400 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000401 }
402
403 for (auto& t : ts) t.join();
404
405 size_t epochMsAfter = epochMillis();
406
Yifan Hong1f44f982021-10-08 17:16:47 -0700407 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000408
409 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700410 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
411}
412
Andrei Homescua858b0e2022-08-01 23:43:09 +0000413TEST_P(BinderRpc, ThreadPoolOverSaturated) {
414 if (clientOrServerSingleThreaded()) {
415 GTEST_SKIP() << "This test requires multiple threads";
416 }
417
Yifan Hong1f44f982021-10-08 17:16:47 -0700418 constexpr size_t kNumThreads = 10;
419 constexpr size_t kNumCalls = kNumThreads + 3;
420 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
421 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
422}
423
Andrei Homescua858b0e2022-08-01 23:43:09 +0000424TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
425 if (clientOrServerSingleThreaded()) {
426 GTEST_SKIP() << "This test requires multiple threads";
427 }
428
Yifan Hong1f44f982021-10-08 17:16:47 -0700429 constexpr size_t kNumThreads = 20;
430 constexpr size_t kNumOutgoingConnections = 10;
431 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
432 auto proc = createRpcTestSocketServerProcess(
433 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
434 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000435}
436
Andrei Homescua858b0e2022-08-01 23:43:09 +0000437TEST_P(BinderRpc, ThreadingStressTest) {
438 if (clientOrServerSingleThreaded()) {
439 GTEST_SKIP() << "This test requires multiple threads";
440 }
441
Steven Moreland5553ac42020-11-11 02:14:45 +0000442 constexpr size_t kNumClientThreads = 10;
443 constexpr size_t kNumServerThreads = 10;
444 constexpr size_t kNumCalls = 100;
445
Steven Moreland4313d7e2021-07-15 23:41:22 +0000446 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000447
448 std::vector<std::thread> threads;
449 for (size_t i = 0; i < kNumClientThreads; i++) {
450 threads.push_back(std::thread([&] {
451 for (size_t j = 0; j < kNumCalls; j++) {
452 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000453 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000454 EXPECT_EQ(proc.rootBinder, out);
455 }
456 }));
457 }
458
459 for (auto& t : threads) t.join();
460}
461
Steven Moreland925ba0a2021-09-17 18:06:32 -0700462static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
463 std::vector<std::thread> threads;
464 for (size_t i = 0; i < threadCount; i++) {
465 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
466 }
467 for (auto& t : threads) t.join();
468}
469
Andrei Homescua858b0e2022-08-01 23:43:09 +0000470TEST_P(BinderRpc, OnewayStressTest) {
471 if (clientOrServerSingleThreaded()) {
472 GTEST_SKIP() << "This test requires multiple threads";
473 }
474
Steven Morelandc6046982021-04-20 00:49:42 +0000475 constexpr size_t kNumClientThreads = 10;
476 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700477 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000478
Steven Moreland4313d7e2021-07-15 23:41:22 +0000479 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000480
481 std::vector<std::thread> threads;
482 for (size_t i = 0; i < kNumClientThreads; i++) {
483 threads.push_back(std::thread([&] {
484 for (size_t j = 0; j < kNumCalls; j++) {
485 EXPECT_OK(proc.rootIface->sendString("a"));
486 }
Steven Morelandc6046982021-04-20 00:49:42 +0000487 }));
488 }
489
490 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700491
492 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000493}
494
Frederick Mayleb0221d12022-10-03 23:10:53 +0000495TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
496 if (!supportsFdTransport()) {
497 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
498 }
499 if (clientOrServerSingleThreaded()) {
500 GTEST_SKIP() << "This test requires multiple threads";
501 }
502
503 // This test forces a oneway transaction to be queued by issuing two
504 // `blockingSendFdOneway` calls, then drains the queue by issuing two
505 // `blockingRecvFd` calls.
506 //
507 // For more details about the queuing semantics see
508 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
509
510 auto proc = createRpcTestSocketServerProcess({
511 .numThreads = 3,
512 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
513 .serverSupportedFileDescriptorTransportModes =
514 {RpcSession::FileDescriptorTransportMode::UNIX},
515 });
516
517 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
518 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
519 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
520 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
521
522 android::os::ParcelFileDescriptor fdA;
523 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
524 std::string result;
525 CHECK(android::base::ReadFdToString(fdA.get(), &result));
526 EXPECT_EQ(result, "a");
527
528 android::os::ParcelFileDescriptor fdB;
529 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
530 CHECK(android::base::ReadFdToString(fdB.get(), &result));
531 EXPECT_EQ(result, "b");
532}
533
Andrei Homescua858b0e2022-08-01 23:43:09 +0000534TEST_P(BinderRpc, OnewayCallQueueing) {
535 if (clientOrServerSingleThreaded()) {
536 GTEST_SKIP() << "This test requires multiple threads";
537 }
538
Steven Moreland5553ac42020-11-11 02:14:45 +0000539 constexpr size_t kNumSleeps = 10;
540 constexpr size_t kNumExtraServerThreads = 4;
541 constexpr size_t kSleepMs = 50;
542
543 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000544 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000545
546 EXPECT_OK(proc.rootIface->lock());
547
Steven Moreland1c678802021-09-17 16:48:47 -0700548 size_t epochMsBefore = epochMillis();
549
550 // all these *Async commands should be queued on the server sequentially,
551 // even though there are multiple threads.
552 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 proc.rootIface->sleepMsAsync(kSleepMs);
554 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000555 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
556
Steven Moreland1c678802021-09-17 16:48:47 -0700557 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000558 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700559
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 size_t epochMsAfter = epochMillis();
561
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000562 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000563
Steven Moreland925ba0a2021-09-17 18:06:32 -0700564 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000565}
566
Andrei Homescua858b0e2022-08-01 23:43:09 +0000567TEST_P(BinderRpc, OnewayCallExhaustion) {
568 if (clientOrServerSingleThreaded()) {
569 GTEST_SKIP() << "This test requires multiple threads";
570 }
571
Steven Morelandd45be622021-06-04 02:19:37 +0000572 constexpr size_t kNumClients = 2;
573 constexpr size_t kTooLongMs = 1000;
574
Steven Moreland4313d7e2021-07-15 23:41:22 +0000575 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000576
577 // Build up oneway calls on the second session to make sure it terminates
578 // and shuts down. The first session should be unaffected (proc destructor
579 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000580 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000581
582 std::vector<std::thread> threads;
583 for (size_t i = 0; i < kNumClients; i++) {
584 // one of these threads will get stuck queueing a transaction once the
585 // socket fills up, the other will be able to fill up transactions on
586 // this object
587 threads.push_back(std::thread([&] {
588 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
589 }
590 }));
591 }
592 for (auto& t : threads) t.join();
593
594 Status status = iface->sleepMsAsync(kTooLongMs);
595 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
596
Steven Moreland798e0d12021-07-14 23:19:25 +0000597 // now that it has died, wait for the remote session to shutdown
598 std::vector<int32_t> remoteCounts;
599 do {
600 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
601 } while (remoteCounts.size() == kNumClients);
602
Steven Morelandd45be622021-06-04 02:19:37 +0000603 // the second session should be shutdown in the other process by the time we
604 // are able to join above (it'll only be hung up once it finishes processing
605 // any pending commands). We need to erase this session from the record
606 // here, so that the destructor for our session won't check that this
607 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000608 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000609}
610
Devin Moore66d5b7a2022-07-07 21:42:10 +0000611TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000612 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000613 GTEST_SKIP() << "This test requires multiple threads";
614 }
615 class MyDeathRec : public IBinder::DeathRecipient {
616 public:
617 void binderDied(const wp<IBinder>& /* who */) override {
618 dead = true;
619 mCv.notify_one();
620 }
621 std::mutex mMtx;
622 std::condition_variable mCv;
623 bool dead = false;
624 };
625
626 // Death recipient needs to have an incoming connection to be called
627 auto proc = createRpcTestSocketServerProcess(
628 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
629
630 auto dr = sp<MyDeathRec>::make();
631 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
632
633 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
634 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
635 }
636
637 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000638 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000639
640 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000641 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000642 proc.expectAlreadyShutdown = true;
643}
644
645TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000646 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000647 GTEST_SKIP() << "This test requires multiple threads";
648 }
649 class MyDeathRec : public IBinder::DeathRecipient {
650 public:
651 void binderDied(const wp<IBinder>& /* who */) override {
652 dead = true;
653 mCv.notify_one();
654 }
655 std::mutex mMtx;
656 std::condition_variable mCv;
657 bool dead = false;
658 };
659
660 // Death recipient needs to have an incoming connection to be called
661 auto proc = createRpcTestSocketServerProcess(
662 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
663
664 auto dr = sp<MyDeathRec>::make();
665 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
666
667 // Explicitly calling shutDownAndWait will cause the death recipients
668 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000669 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000670
671 std::unique_lock<std::mutex> lock(dr->mMtx);
672 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000673 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000674 }
675 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
676
Andrei Homescu96834632022-10-14 00:49:49 +0000677 proc.proc->terminate();
678 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000679 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
680 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
681 });
682 proc.expectAlreadyShutdown = true;
683}
684
685TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
686 class MyDeathRec : public IBinder::DeathRecipient {
687 public:
688 void binderDied(const wp<IBinder>& /* who */) override {}
689 };
690
691 auto proc = createRpcTestSocketServerProcess(
692 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
693
694 auto dr = sp<MyDeathRec>::make();
695 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
696 "Cannot register a DeathRecipient without any incoming connections.");
697}
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
Frederick Mayledc07cf82022-05-26 20:30:12 +00001103static std::vector<uint32_t> testVersions() {
1104 std::vector<uint32_t> versions;
1105 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1106 versions.push_back(i);
1107 }
1108 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1109 return versions;
1110}
1111
Yifan Hong702115c2021-06-24 15:39:18 -07001112INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1113 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001114 ::testing::ValuesIn(RpcSecurityValues()),
1115 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001116 ::testing::ValuesIn(testVersions()),
1117 ::testing::Values(false, true),
1118 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001119 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001120
Yifan Hong702115c2021-06-24 15:39:18 -07001121class BinderRpcServerRootObject
1122 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001123
1124TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1125 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1126 auto setRootObject = [](bool isStrong) -> SetFn {
1127 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1128 };
1129
Yifan Hong702115c2021-06-24 15:39:18 -07001130 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1131 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001132 auto binder1 = sp<BBinder>::make();
1133 IBinder* binderRaw1 = binder1.get();
1134 setRootObject(isStrong1)(server.get(), binder1);
1135 EXPECT_EQ(binderRaw1, server->getRootObject());
1136 binder1.clear();
1137 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1138
1139 auto binder2 = sp<BBinder>::make();
1140 IBinder* binderRaw2 = binder2.get();
1141 setRootObject(isStrong2)(server.get(), binder2);
1142 EXPECT_EQ(binderRaw2, server->getRootObject());
1143 binder2.clear();
1144 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1145}
1146
1147INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001148 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1149 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001150
Yifan Hong1a235852021-05-13 16:07:47 -07001151class OneOffSignal {
1152public:
1153 // If notify() was previously called, or is called within |duration|, return true; else false.
1154 template <typename R, typename P>
1155 bool wait(std::chrono::duration<R, P> duration) {
1156 std::unique_lock<std::mutex> lock(mMutex);
1157 return mCv.wait_for(lock, duration, [this] { return mValue; });
1158 }
1159 void notify() {
1160 std::unique_lock<std::mutex> lock(mMutex);
1161 mValue = true;
1162 lock.unlock();
1163 mCv.notify_all();
1164 }
1165
1166private:
1167 std::mutex mMutex;
1168 std::condition_variable mCv;
1169 bool mValue = false;
1170};
1171
Yifan Hong194acf22021-06-29 18:44:56 -07001172TEST(BinderRpc, Java) {
1173#if !defined(__ANDROID__)
1174 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1175 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1176 "to binderHostDeviceTest. Hence, just disable this test on host.";
1177#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001178 if constexpr (!kEnableKernelIpc) {
1179 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1180 "at build time.";
1181 }
1182
Yifan Hong194acf22021-06-29 18:44:56 -07001183 sp<IServiceManager> sm = defaultServiceManager();
1184 ASSERT_NE(nullptr, sm);
1185 // Any Java service with non-empty getInterfaceDescriptor() would do.
1186 // Let's pick batteryproperties.
1187 auto binder = sm->checkService(String16("batteryproperties"));
1188 ASSERT_NE(nullptr, binder);
1189 auto descriptor = binder->getInterfaceDescriptor();
1190 ASSERT_GE(descriptor.size(), 0);
1191 ASSERT_EQ(OK, binder->pingBinder());
1192
1193 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001194 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001195 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001196 auto socket = rpcServer->releaseServer();
1197
1198 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001199 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1200
Yifan Honge3caaf22022-01-12 14:46:56 -08001201 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1202 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001203 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001204 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1205 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001206 << statusToString(setRpcClientDebugStatus);
1207 GTEST_SKIP();
1208 }
1209
1210 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001211
1212 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001213 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001214 auto rpcBinder = rpcSession->getRootObject();
1215 ASSERT_NE(nullptr, rpcBinder);
1216
1217 ASSERT_EQ(OK, rpcBinder->pingBinder());
1218
1219 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1220 << "getInterfaceDescriptor should not crash system_server";
1221 ASSERT_EQ(OK, rpcBinder->pingBinder());
1222}
1223
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001224class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1225public:
1226 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1227 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1228 std::to_string(std::get<1>(info.param));
1229 }
1230};
1231
1232TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1233 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1234 int sinkFd = sink.get();
1235 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1236 server->setProtocolVersion(std::get<1>(GetParam()));
1237 ASSERT_FALSE(server->hasServer());
1238 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1239 ASSERT_TRUE(server->hasServer());
1240 base::unique_fd retrieved = server->releaseServer();
1241 ASSERT_FALSE(server->hasServer());
1242 ASSERT_EQ(sinkFd, retrieved.get());
1243}
1244
1245TEST_P(BinderRpcServerOnly, Shutdown) {
1246 if constexpr (!kEnableRpcThreads) {
1247 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1248 }
1249
1250 auto addr = allocateSocketAddress();
1251 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1252 server->setProtocolVersion(std::get<1>(GetParam()));
1253 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1254 auto joinEnds = std::make_shared<OneOffSignal>();
1255
1256 // If things are broken and the thread never stops, don't block other tests. Because the thread
1257 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1258 // shared pointers are passed.
1259 std::thread([server, joinEnds] {
1260 server->join();
1261 joinEnds->notify();
1262 }).detach();
1263
1264 bool shutdown = false;
1265 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001266 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001267 if (server->shutdown()) shutdown = true;
1268 }
1269 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1270
1271 ASSERT_TRUE(joinEnds->wait(2s))
1272 << "After server->shutdown() returns true, join() did not stop after 2s";
1273}
1274
Frederick Mayledc07cf82022-05-26 20:30:12 +00001275INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1276 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1277 ::testing::ValuesIn(testVersions())),
1278 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001279
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001280class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001281public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001282 // Only parameterized only server version because `RpcSession` is bypassed
1283 // in the client half of the tests.
1284 using Param =
1285 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001286 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001287
1288 // A server that handles client socket connections.
1289 class Server {
1290 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001291 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1292
Yifan Hong1deca4b2021-09-10 16:16:44 -07001293 explicit Server() {}
1294 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001295 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001296 [[nodiscard]] AssertionResult setUp(
1297 const Param& param,
1298 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001299 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001300 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001301 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001302 switch (socketType) {
1303 case SocketType::PRECONNECTED: {
1304 return AssertionFailure() << "Not supported by this test";
1305 } break;
1306 case SocketType::UNIX: {
1307 auto addr = allocateSocketAddress();
1308 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1309 if (status != OK) {
1310 return AssertionFailure()
1311 << "setupUnixDomainServer: " << statusToString(status);
1312 }
1313 mConnectToServer = [addr] {
1314 return connectTo(UnixSocketAddress(addr.c_str()));
1315 };
1316 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001317 case SocketType::UNIX_BOOTSTRAP: {
1318 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1319 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1320 return AssertionFailure() << "Socketpair() failed";
1321 }
1322 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1323 std::move(bootstrapFdServer));
1324 if (status != OK) {
1325 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1326 << statusToString(status);
1327 }
1328 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1329 mAcceptConnection = &Server::recvmsgServerConnection;
1330 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1331 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001332 case SocketType::UNIX_RAW: {
1333 auto addr = allocateSocketAddress();
1334 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1335 if (status != OK) {
1336 return AssertionFailure()
1337 << "setupRawSocketServer: " << statusToString(status);
1338 }
1339 mConnectToServer = [addr] {
1340 return connectTo(UnixSocketAddress(addr.c_str()));
1341 };
1342 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001343 case SocketType::VSOCK: {
1344 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001345 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001346 if (status != OK) {
1347 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1348 }
1349 mConnectToServer = [port] {
1350 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1351 };
1352 } break;
1353 case SocketType::INET: {
1354 unsigned int port;
1355 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1356 if (status != OK) {
1357 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1358 }
1359 mConnectToServer = [port] {
1360 const char* addr = kLocalInetAddress;
1361 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1362 if (aiStart == nullptr) return base::unique_fd{};
1363 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1364 auto fd = connectTo(
1365 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1366 if (fd.ok()) return fd;
1367 }
1368 ALOGE("None of the socket address resolved for %s:%u can be connected",
1369 addr, port);
1370 return base::unique_fd{};
1371 };
1372 }
1373 }
1374 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001375 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001376 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001377 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1378 mSetup = true;
1379 return AssertionSuccess();
1380 }
1381 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1382 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1383 return mCertVerifier;
1384 }
1385 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1386 void start() {
1387 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1388 mThread = std::make_unique<std::thread>(&Server::run, this);
1389 }
David Brazdil21c887c2022-09-23 12:25:18 +01001390
1391 base::unique_fd acceptServerConnection() {
1392 return base::unique_fd(TEMP_FAILURE_RETRY(
1393 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1394 }
1395
1396 base::unique_fd recvmsgServerConnection() {
1397 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1398 int buf;
1399 iovec iov{&buf, sizeof(buf)};
1400
1401 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1402 int savedErrno = errno;
1403 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1404 }
1405 if (fds.size() != 1) {
1406 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1407 }
1408 return std::move(std::get<base::unique_fd>(fds[0]));
1409 }
1410
Yifan Hong1deca4b2021-09-10 16:16:44 -07001411 void run() {
1412 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1413
1414 std::vector<std::thread> threads;
1415 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001416 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001417 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1418 }
1419
1420 for (auto& thread : threads) thread.join();
1421 }
1422 void handleOne(android::base::unique_fd acceptedFd) {
1423 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001424 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001425 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001426 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001427 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001428 }
Yifan Honge07d2732021-09-13 21:59:14 -07001429 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001430 shutdown();
1431 join();
1432 }
1433 void shutdown() { mFdTrigger->trigger(); }
1434
1435 void setPostConnect(
1436 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1437 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001438 }
1439
1440 private:
1441 std::unique_ptr<std::thread> mThread;
1442 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001443 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001444 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001445 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001446 std::unique_ptr<RpcTransportCtx> mCtx;
1447 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1448 std::make_shared<RpcCertificateVerifierSimple>();
1449 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001450 // The function invoked after connection and handshake. By default, it is
1451 // |defaultPostConnect| that sends |kMessage| to the client.
1452 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1453 Server::defaultPostConnect;
1454
1455 void join() {
1456 if (mThread != nullptr) {
1457 mThread->join();
1458 mThread = nullptr;
1459 }
1460 }
1461
1462 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1463 FdTrigger* fdTrigger) {
1464 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001465 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001466 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001467 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001468 if (status != OK) return AssertionFailure() << statusToString(status);
1469 return AssertionSuccess();
1470 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001471 };
1472
1473 class Client {
1474 public:
1475 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1476 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001477 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001478 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1479 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001480 mFdTrigger = FdTrigger::make();
1481 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1482 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1483 return AssertionSuccess();
1484 }
1485 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1486 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1487 return mCertVerifier;
1488 }
Yifan Hong67519322021-09-13 18:51:16 -07001489 // connect() and do handshake
1490 bool setUpTransport() {
1491 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001492 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001493 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1494 return mClientTransport != nullptr;
1495 }
1496 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1497 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1498 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001499 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001500 status_t readStatus =
1501 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001502 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001503 if (readStatus != OK) {
1504 return AssertionFailure() << statusToString(readStatus);
1505 }
1506 if (readMessage != expectedMessage) {
1507 return AssertionFailure()
1508 << "Expected " << expectedMessage << ", actual " << readMessage;
1509 }
1510 return AssertionSuccess();
1511 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001512 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001513 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001514 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1515 return;
1516 }
1517 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001518 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001519 }
1520
Pawan49d74cb2022-08-03 21:19:11 +00001521 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1522
Yifan Hong1deca4b2021-09-10 16:16:44 -07001523 private:
1524 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001525 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001526 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1527 std::unique_ptr<RpcTransportCtx> mCtx;
1528 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1529 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001530 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001531 };
1532
1533 // Make A trust B.
1534 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001535 static status_t trust(RpcSecurity rpcSecurity,
1536 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1537 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001538 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001539 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1540 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1541 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001542 }
1543
1544 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001545};
1546
1547class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1548public:
1549 using Server = RpcTransportTestUtils::Server;
1550 using Client = RpcTransportTestUtils::Client;
1551 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001552 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001553 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1554 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001555 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001556 return ret;
1557 }
1558 static std::vector<ParamType> getRpcTranportTestParams() {
1559 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001560 for (auto serverVersion : testVersions()) {
1561 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1562 for (auto rpcSecurity : RpcSecurityValues()) {
1563 switch (rpcSecurity) {
1564 case RpcSecurity::RAW: {
1565 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1566 } break;
1567 case RpcSecurity::TLS: {
1568 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1569 serverVersion);
1570 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1571 serverVersion);
1572 } break;
1573 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001574 }
1575 }
1576 }
1577 return ret;
1578 }
1579 template <typename A, typename B>
1580 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001581 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1582 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001583 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1584 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001585 void SetUp() override {
1586 if constexpr (!kEnableRpcThreads) {
1587 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1588 }
1589 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001590};
1591
1592TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001593 auto server = std::make_unique<Server>();
1594 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001595
1596 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001597 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001598
1599 ASSERT_EQ(OK, trust(&client, server));
1600 ASSERT_EQ(OK, trust(server, &client));
1601
1602 server->start();
1603 client.run();
1604}
1605
1606TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001607 auto server = std::make_unique<Server>();
1608 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001609
1610 std::vector<Client> clients;
1611 for (int i = 0; i < 2; i++) {
1612 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001613 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001614 ASSERT_EQ(OK, trust(&client, server));
1615 ASSERT_EQ(OK, trust(server, &client));
1616 }
1617
1618 server->start();
1619 for (auto& client : clients) client.run();
1620}
1621
1622TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001623 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1624 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001626 auto untrustedServer = std::make_unique<Server>();
1627 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001628
1629 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001630 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001631
1632 ASSERT_EQ(OK, trust(untrustedServer, &client));
1633
1634 untrustedServer->start();
1635
1636 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1637 // the client can't verify the server's identity.
1638 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1639 client.run(handshakeOk);
1640}
1641TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001642 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1643 (void)serverVersion;
1644
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001645 auto validServer = std::make_unique<Server>();
1646 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001647
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001648 auto maliciousServer = std::make_unique<Server>();
1649 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001650
1651 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001652 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001653
1654 ASSERT_EQ(OK, trust(&client, validServer));
1655 ASSERT_EQ(OK, trust(validServer, &client));
1656 ASSERT_EQ(OK, trust(maliciousServer, &client));
1657
1658 maliciousServer->start();
1659
1660 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1661 // the client can't verify the server's identity.
1662 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1663 client.run(handshakeOk);
1664}
1665
1666TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001667 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1668 (void)serverVersion;
1669
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001670 auto server = std::make_unique<Server>();
1671 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001672
1673 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001674 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001675
1676 ASSERT_EQ(OK, trust(&client, server));
1677
1678 server->start();
1679
1680 // For TLS, Client should be able to verify server's identity, so client should see
1681 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1682 // identity and should drop the connection, so client shouldn't be able to read anything.
1683 bool readOk = rpcSecurity != RpcSecurity::TLS;
1684 client.run(true, readOk);
1685}
1686
1687TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001688 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1689 (void)serverVersion;
1690
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001691 auto server = std::make_unique<Server>();
1692 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001693
1694 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001695 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001696 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001697 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001698
1699 ASSERT_EQ(OK, trust(&validClient, server));
1700 ASSERT_EQ(OK, trust(&maliciousClient, server));
1701
1702 server->start();
1703
1704 // See UntrustedClient.
1705 bool readOk = rpcSecurity != RpcSecurity::TLS;
1706 maliciousClient.run(true, readOk);
1707}
1708
Yifan Hong67519322021-09-13 18:51:16 -07001709TEST_P(RpcTransportTest, Trigger) {
1710 std::string msg2 = ", world!";
1711 std::mutex writeMutex;
1712 std::condition_variable writeCv;
1713 bool shouldContinueWriting = false;
1714 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001715 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001716 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001717 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1718 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001719 if (status != OK) return AssertionFailure() << statusToString(status);
1720
1721 {
1722 std::unique_lock<std::mutex> lock(writeMutex);
1723 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1724 return AssertionFailure() << "write barrier not cleared in time!";
1725 }
1726 }
1727
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001728 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001729 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1730 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001731 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001732 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001733 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001734 << statusToString(status);
1735 return AssertionSuccess();
1736 };
1737
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001738 auto server = std::make_unique<Server>();
1739 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001740
1741 // Set up client
1742 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001743 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001744
1745 // Exchange keys
1746 ASSERT_EQ(OK, trust(&client, server));
1747 ASSERT_EQ(OK, trust(server, &client));
1748
1749 server->setPostConnect(serverPostConnect);
1750
Yifan Hong67519322021-09-13 18:51:16 -07001751 server->start();
1752 // connect() to server and do handshake
1753 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001754 // read the first message. This ensures that server has finished handshake and start handling
1755 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001756 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001757 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1758 // write is on an FdTrigger that has been shut down.
1759 server->shutdown();
1760 // Continues server thread to write the second message.
1761 {
Yifan Hong22211f82021-09-14 12:32:25 -07001762 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001763 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001764 }
Yifan Hong22211f82021-09-14 12:32:25 -07001765 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001766 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001767 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001768 // On the client side, second read fails with DEAD_OBJECT
1769 ASSERT_FALSE(client.readMessage(msg2));
1770}
1771
Pawan49d74cb2022-08-03 21:19:11 +00001772TEST_P(RpcTransportTest, CheckWaitingForRead) {
1773 std::mutex readMutex;
1774 std::condition_variable readCv;
1775 bool shouldContinueReading = false;
1776 // Server will write data on transport once its started
1777 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1778 std::string message(RpcTransportTestUtils::kMessage);
1779 iovec messageIov{message.data(), message.size()};
1780 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1781 std::nullopt, nullptr);
1782 if (status != OK) return AssertionFailure() << statusToString(status);
1783
1784 {
1785 std::unique_lock<std::mutex> lock(readMutex);
1786 shouldContinueReading = true;
1787 lock.unlock();
1788 readCv.notify_all();
1789 }
1790 return AssertionSuccess();
1791 };
1792
1793 // Setup Server and client
1794 auto server = std::make_unique<Server>();
1795 ASSERT_TRUE(server->setUp(GetParam()));
1796
1797 Client client(server->getConnectToServerFn());
1798 ASSERT_TRUE(client.setUp(GetParam()));
1799
1800 ASSERT_EQ(OK, trust(&client, server));
1801 ASSERT_EQ(OK, trust(server, &client));
1802 server->setPostConnect(serverPostConnect);
1803
1804 server->start();
1805 ASSERT_TRUE(client.setUpTransport());
1806 {
1807 // Wait till server writes data
1808 std::unique_lock<std::mutex> lock(readMutex);
1809 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1810 }
1811
1812 // Since there is no read polling here, we will get polling count 0
1813 ASSERT_FALSE(client.isTransportWaiting());
1814 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1815 // Thread should increment polling count, read and decrement polling count
1816 // Again, polling count should be zero here
1817 ASSERT_FALSE(client.isTransportWaiting());
1818
1819 server->shutdown();
1820}
1821
Yifan Hong1deca4b2021-09-10 16:16:44 -07001822INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001823 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824 RpcTransportTest::PrintParamInfo);
1825
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001826class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001827 : public testing::TestWithParam<
1828 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001829public:
1830 template <typename A, typename B>
1831 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001832 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1833 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001834 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1835 }
1836 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001837 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1838 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1839 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001840 };
1841};
1842
1843TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001844 if constexpr (!kEnableRpcThreads) {
1845 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1846 }
1847
Frederick Mayledc07cf82022-05-26 20:30:12 +00001848 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849
1850 std::vector<uint8_t> pkeyData, certData;
1851 {
1852 auto pkey = makeKeyPairForSelfSignedCert();
1853 ASSERT_NE(nullptr, pkey);
1854 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1855 ASSERT_NE(nullptr, cert);
1856 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1857 certData = serializeCertificate(cert.get(), certificateFormat);
1858 }
1859
1860 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1861 auto desCert = deserializeCertificate(certData, certificateFormat);
1862 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001863 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1864 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001865
1866 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1867 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1868
1869 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1870 ASSERT_TRUE(client.setUp(utilsParam));
1871
1872 ASSERT_EQ(OK, trust(&client, server));
1873 ASSERT_EQ(OK, trust(server, &client));
1874
1875 server->start();
1876 client.run();
1877}
1878
1879INSTANTIATE_TEST_CASE_P(
1880 BinderRpc, RpcTransportTlsKeyTest,
1881 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1882 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001883 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1884 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001885 RpcTransportTlsKeyTest::PrintParamInfo);
1886
Steven Morelandc1635952021-04-01 16:20:47 +00001887} // namespace android
1888
1889int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001890 ::testing::InitGoogleTest(&argc, argv);
1891 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001892
Steven Moreland5553ac42020-11-11 02:14:45 +00001893 return RUN_ALL_TESTS();
1894}