blob: 68a827bb3e6ac830757d77442d88b860716fd1d5 [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
Steven Moreland37aff182021-03-26 02:04:16 +0000916TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000917 if constexpr (!kEnableSharedLibs) {
918 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
919 }
920
Steven Moreland4313d7e2021-07-15 23:41:22 +0000921 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000922
923 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
924 ASSERT_NE(binder, nullptr);
925
926 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
927}
928
929TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000930 if constexpr (!kEnableSharedLibs) {
931 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
932 }
933
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000935
936 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
937 ASSERT_NE(binder, nullptr);
938
939 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
940 ASSERT_NE(ndkBinder, nullptr);
941
942 std::string out;
943 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
944 ASSERT_TRUE(status.isOk()) << status.getDescription();
945 ASSERT_EQ("aoeuaoeu", out);
946}
947
Steven Moreland5553ac42020-11-11 02:14:45 +0000948ssize_t countFds() {
949 DIR* dir = opendir("/proc/self/fd/");
950 if (dir == nullptr) return -1;
951 ssize_t ret = 0;
952 dirent* ent;
953 while ((ent = readdir(dir)) != nullptr) ret++;
954 closedir(dir);
955 return ret;
956}
957
Andrei Homescua858b0e2022-08-01 23:43:09 +0000958TEST_P(BinderRpc, Fds) {
959 if (serverSingleThreaded()) {
960 GTEST_SKIP() << "This test requires multiple threads";
961 }
962
Steven Moreland5553ac42020-11-11 02:14:45 +0000963 ssize_t beforeFds = countFds();
964 ASSERT_GE(beforeFds, 0);
965 {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000966 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +0000967 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
968 }
969 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
970}
971
Steven Morelandda573042021-06-12 01:13:45 +0000972static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -0700973 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +0000974 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +0000975
Andrei Homescu992a4052022-06-28 21:26:18 +0000976 android::base::unique_fd serverFd(
977 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
978 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
979
980 sockaddr_vm serverAddr{
981 .svm_family = AF_VSOCK,
982 .svm_port = vsockPort,
983 .svm_cid = VMADDR_CID_ANY,
984 };
985 int ret = TEMP_FAILURE_RETRY(
986 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
987 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
988 strerror(errno));
989
990 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
991 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
992 strerror(errno));
993
994 // Try to connect to the server using the VMADDR_CID_LOCAL cid
995 // to see if the kernel supports it. It's safe to use a blocking
996 // connect because vsock sockets have a 2 second connection timeout,
997 // and they return ETIMEDOUT after that.
998 android::base::unique_fd connectFd(
999 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1000 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1001 strerror(errno));
1002
1003 bool success = false;
1004 sockaddr_vm connectAddr{
1005 .svm_family = AF_VSOCK,
1006 .svm_port = vsockPort,
1007 .svm_cid = VMADDR_CID_LOCAL,
1008 };
1009 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1010 sizeof(connectAddr)));
1011 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1012 android::base::unique_fd acceptFd;
1013 while (true) {
1014 pollfd pfd[]{
1015 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1016 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1017 };
1018 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1019 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1020
1021 if (pfd[0].revents & POLLIN) {
1022 sockaddr_vm acceptAddr;
1023 socklen_t acceptAddrLen = sizeof(acceptAddr);
1024 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1025 reinterpret_cast<sockaddr*>(&acceptAddr),
1026 &acceptAddrLen, SOCK_CLOEXEC));
1027 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1028 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1029 "Truncated address");
1030
1031 // Store the fd in acceptFd so we keep the connection alive
1032 // while polling connectFd
1033 acceptFd.reset(ret);
1034 }
1035
1036 if (pfd[1].revents & POLLOUT) {
1037 // Connect either succeeded or timed out
1038 int connectErrno;
1039 socklen_t connectErrnoLen = sizeof(connectErrno);
1040 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1041 &connectErrnoLen);
1042 LOG_ALWAYS_FATAL_IF(ret == -1,
1043 "Could not getsockopt() after connect() "
1044 "on non-blocking socket: %s.",
1045 strerror(errno));
1046
1047 // We're done, this is all we wanted
1048 success = connectErrno == 0;
1049 break;
1050 }
1051 }
1052 } else {
1053 success = ret == 0;
1054 }
1055
1056 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1057
1058 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001059}
1060
Yifan Hong1deca4b2021-09-10 16:16:44 -07001061static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001062 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1063 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001064
1065 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001066
1067 static bool hasVsockLoopback = testSupportVsockLoopback();
1068
1069 if (hasVsockLoopback) {
1070 ret.push_back(SocketType::VSOCK);
1071 }
1072
1073 return ret;
1074}
1075
Frederick Mayledc07cf82022-05-26 20:30:12 +00001076static std::vector<uint32_t> testVersions() {
1077 std::vector<uint32_t> versions;
1078 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1079 versions.push_back(i);
1080 }
1081 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1082 return versions;
1083}
1084
Yifan Hong702115c2021-06-24 15:39:18 -07001085INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1086 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001087 ::testing::ValuesIn(RpcSecurityValues()),
1088 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001089 ::testing::ValuesIn(testVersions()),
1090 ::testing::Values(false, true),
1091 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001092 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001093
Yifan Hong702115c2021-06-24 15:39:18 -07001094class BinderRpcServerRootObject
1095 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001096
1097TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1098 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1099 auto setRootObject = [](bool isStrong) -> SetFn {
1100 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1101 };
1102
Yifan Hong702115c2021-06-24 15:39:18 -07001103 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1104 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001105 auto binder1 = sp<BBinder>::make();
1106 IBinder* binderRaw1 = binder1.get();
1107 setRootObject(isStrong1)(server.get(), binder1);
1108 EXPECT_EQ(binderRaw1, server->getRootObject());
1109 binder1.clear();
1110 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1111
1112 auto binder2 = sp<BBinder>::make();
1113 IBinder* binderRaw2 = binder2.get();
1114 setRootObject(isStrong2)(server.get(), binder2);
1115 EXPECT_EQ(binderRaw2, server->getRootObject());
1116 binder2.clear();
1117 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1118}
1119
1120INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001121 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1122 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001123
Yifan Hong1a235852021-05-13 16:07:47 -07001124class OneOffSignal {
1125public:
1126 // If notify() was previously called, or is called within |duration|, return true; else false.
1127 template <typename R, typename P>
1128 bool wait(std::chrono::duration<R, P> duration) {
1129 std::unique_lock<std::mutex> lock(mMutex);
1130 return mCv.wait_for(lock, duration, [this] { return mValue; });
1131 }
1132 void notify() {
1133 std::unique_lock<std::mutex> lock(mMutex);
1134 mValue = true;
1135 lock.unlock();
1136 mCv.notify_all();
1137 }
1138
1139private:
1140 std::mutex mMutex;
1141 std::condition_variable mCv;
1142 bool mValue = false;
1143};
1144
Yifan Hong194acf22021-06-29 18:44:56 -07001145TEST(BinderRpc, Java) {
1146#if !defined(__ANDROID__)
1147 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1148 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1149 "to binderHostDeviceTest. Hence, just disable this test on host.";
1150#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001151 if constexpr (!kEnableKernelIpc) {
1152 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1153 "at build time.";
1154 }
1155
Yifan Hong194acf22021-06-29 18:44:56 -07001156 sp<IServiceManager> sm = defaultServiceManager();
1157 ASSERT_NE(nullptr, sm);
1158 // Any Java service with non-empty getInterfaceDescriptor() would do.
1159 // Let's pick batteryproperties.
1160 auto binder = sm->checkService(String16("batteryproperties"));
1161 ASSERT_NE(nullptr, binder);
1162 auto descriptor = binder->getInterfaceDescriptor();
1163 ASSERT_GE(descriptor.size(), 0);
1164 ASSERT_EQ(OK, binder->pingBinder());
1165
1166 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001167 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001168 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001169 auto socket = rpcServer->releaseServer();
1170
1171 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001172 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1173
Yifan Honge3caaf22022-01-12 14:46:56 -08001174 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1175 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001176 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001177 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1178 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001179 << statusToString(setRpcClientDebugStatus);
1180 GTEST_SKIP();
1181 }
1182
1183 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001184
1185 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001186 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001187 auto rpcBinder = rpcSession->getRootObject();
1188 ASSERT_NE(nullptr, rpcBinder);
1189
1190 ASSERT_EQ(OK, rpcBinder->pingBinder());
1191
1192 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1193 << "getInterfaceDescriptor should not crash system_server";
1194 ASSERT_EQ(OK, rpcBinder->pingBinder());
1195}
1196
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001197class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1198public:
1199 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1200 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1201 std::to_string(std::get<1>(info.param));
1202 }
1203};
1204
1205TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1206 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1207 int sinkFd = sink.get();
1208 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1209 server->setProtocolVersion(std::get<1>(GetParam()));
1210 ASSERT_FALSE(server->hasServer());
1211 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1212 ASSERT_TRUE(server->hasServer());
1213 base::unique_fd retrieved = server->releaseServer();
1214 ASSERT_FALSE(server->hasServer());
1215 ASSERT_EQ(sinkFd, retrieved.get());
1216}
1217
1218TEST_P(BinderRpcServerOnly, Shutdown) {
1219 if constexpr (!kEnableRpcThreads) {
1220 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1221 }
1222
1223 auto addr = allocateSocketAddress();
1224 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1225 server->setProtocolVersion(std::get<1>(GetParam()));
1226 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1227 auto joinEnds = std::make_shared<OneOffSignal>();
1228
1229 // If things are broken and the thread never stops, don't block other tests. Because the thread
1230 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1231 // shared pointers are passed.
1232 std::thread([server, joinEnds] {
1233 server->join();
1234 joinEnds->notify();
1235 }).detach();
1236
1237 bool shutdown = false;
1238 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001239 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001240 if (server->shutdown()) shutdown = true;
1241 }
1242 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1243
1244 ASSERT_TRUE(joinEnds->wait(2s))
1245 << "After server->shutdown() returns true, join() did not stop after 2s";
1246}
1247
Frederick Mayledc07cf82022-05-26 20:30:12 +00001248INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1249 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1250 ::testing::ValuesIn(testVersions())),
1251 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001252
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001253class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001254public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001255 // Only parameterized only server version because `RpcSession` is bypassed
1256 // in the client half of the tests.
1257 using Param =
1258 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001259 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001260
1261 // A server that handles client socket connections.
1262 class Server {
1263 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001264 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1265
Yifan Hong1deca4b2021-09-10 16:16:44 -07001266 explicit Server() {}
1267 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001268 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001269 [[nodiscard]] AssertionResult setUp(
1270 const Param& param,
1271 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001272 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001273 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001274 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001275 switch (socketType) {
1276 case SocketType::PRECONNECTED: {
1277 return AssertionFailure() << "Not supported by this test";
1278 } break;
1279 case SocketType::UNIX: {
1280 auto addr = allocateSocketAddress();
1281 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1282 if (status != OK) {
1283 return AssertionFailure()
1284 << "setupUnixDomainServer: " << statusToString(status);
1285 }
1286 mConnectToServer = [addr] {
1287 return connectTo(UnixSocketAddress(addr.c_str()));
1288 };
1289 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001290 case SocketType::UNIX_BOOTSTRAP: {
1291 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1292 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1293 return AssertionFailure() << "Socketpair() failed";
1294 }
1295 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1296 std::move(bootstrapFdServer));
1297 if (status != OK) {
1298 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1299 << statusToString(status);
1300 }
1301 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1302 mAcceptConnection = &Server::recvmsgServerConnection;
1303 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1304 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001305 case SocketType::UNIX_RAW: {
1306 auto addr = allocateSocketAddress();
1307 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1308 if (status != OK) {
1309 return AssertionFailure()
1310 << "setupRawSocketServer: " << statusToString(status);
1311 }
1312 mConnectToServer = [addr] {
1313 return connectTo(UnixSocketAddress(addr.c_str()));
1314 };
1315 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001316 case SocketType::VSOCK: {
1317 auto port = allocateVsockPort();
1318 auto status = rpcServer->setupVsockServer(port);
1319 if (status != OK) {
1320 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1321 }
1322 mConnectToServer = [port] {
1323 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1324 };
1325 } break;
1326 case SocketType::INET: {
1327 unsigned int port;
1328 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1329 if (status != OK) {
1330 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1331 }
1332 mConnectToServer = [port] {
1333 const char* addr = kLocalInetAddress;
1334 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1335 if (aiStart == nullptr) return base::unique_fd{};
1336 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1337 auto fd = connectTo(
1338 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1339 if (fd.ok()) return fd;
1340 }
1341 ALOGE("None of the socket address resolved for %s:%u can be connected",
1342 addr, port);
1343 return base::unique_fd{};
1344 };
1345 }
1346 }
1347 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001348 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001349 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001350 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1351 mSetup = true;
1352 return AssertionSuccess();
1353 }
1354 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1355 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1356 return mCertVerifier;
1357 }
1358 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1359 void start() {
1360 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1361 mThread = std::make_unique<std::thread>(&Server::run, this);
1362 }
David Brazdil21c887c2022-09-23 12:25:18 +01001363
1364 base::unique_fd acceptServerConnection() {
1365 return base::unique_fd(TEMP_FAILURE_RETRY(
1366 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1367 }
1368
1369 base::unique_fd recvmsgServerConnection() {
1370 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1371 int buf;
1372 iovec iov{&buf, sizeof(buf)};
1373
1374 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1375 int savedErrno = errno;
1376 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1377 }
1378 if (fds.size() != 1) {
1379 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1380 }
1381 return std::move(std::get<base::unique_fd>(fds[0]));
1382 }
1383
Yifan Hong1deca4b2021-09-10 16:16:44 -07001384 void run() {
1385 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1386
1387 std::vector<std::thread> threads;
1388 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001389 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001390 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1391 }
1392
1393 for (auto& thread : threads) thread.join();
1394 }
1395 void handleOne(android::base::unique_fd acceptedFd) {
1396 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001397 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001398 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001399 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001400 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001401 }
Yifan Honge07d2732021-09-13 21:59:14 -07001402 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001403 shutdown();
1404 join();
1405 }
1406 void shutdown() { mFdTrigger->trigger(); }
1407
1408 void setPostConnect(
1409 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1410 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001411 }
1412
1413 private:
1414 std::unique_ptr<std::thread> mThread;
1415 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001416 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001417 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001418 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001419 std::unique_ptr<RpcTransportCtx> mCtx;
1420 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1421 std::make_shared<RpcCertificateVerifierSimple>();
1422 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001423 // The function invoked after connection and handshake. By default, it is
1424 // |defaultPostConnect| that sends |kMessage| to the client.
1425 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1426 Server::defaultPostConnect;
1427
1428 void join() {
1429 if (mThread != nullptr) {
1430 mThread->join();
1431 mThread = nullptr;
1432 }
1433 }
1434
1435 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1436 FdTrigger* fdTrigger) {
1437 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001438 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001439 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001440 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001441 if (status != OK) return AssertionFailure() << statusToString(status);
1442 return AssertionSuccess();
1443 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001444 };
1445
1446 class Client {
1447 public:
1448 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1449 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001450 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001451 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1452 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001453 mFdTrigger = FdTrigger::make();
1454 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1455 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1456 return AssertionSuccess();
1457 }
1458 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1459 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1460 return mCertVerifier;
1461 }
Yifan Hong67519322021-09-13 18:51:16 -07001462 // connect() and do handshake
1463 bool setUpTransport() {
1464 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001465 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001466 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1467 return mClientTransport != nullptr;
1468 }
1469 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1470 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1471 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001472 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001473 status_t readStatus =
1474 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001475 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001476 if (readStatus != OK) {
1477 return AssertionFailure() << statusToString(readStatus);
1478 }
1479 if (readMessage != expectedMessage) {
1480 return AssertionFailure()
1481 << "Expected " << expectedMessage << ", actual " << readMessage;
1482 }
1483 return AssertionSuccess();
1484 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001485 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001486 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001487 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1488 return;
1489 }
1490 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001491 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001492 }
1493
Pawan49d74cb2022-08-03 21:19:11 +00001494 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1495
Yifan Hong1deca4b2021-09-10 16:16:44 -07001496 private:
1497 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001498 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001499 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1500 std::unique_ptr<RpcTransportCtx> mCtx;
1501 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1502 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001503 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001504 };
1505
1506 // Make A trust B.
1507 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001508 static status_t trust(RpcSecurity rpcSecurity,
1509 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1510 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001511 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001512 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1513 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1514 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001515 }
1516
1517 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001518};
1519
1520class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1521public:
1522 using Server = RpcTransportTestUtils::Server;
1523 using Client = RpcTransportTestUtils::Client;
1524 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001525 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001526 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1527 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001528 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001529 return ret;
1530 }
1531 static std::vector<ParamType> getRpcTranportTestParams() {
1532 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001533 for (auto serverVersion : testVersions()) {
1534 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1535 for (auto rpcSecurity : RpcSecurityValues()) {
1536 switch (rpcSecurity) {
1537 case RpcSecurity::RAW: {
1538 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1539 } break;
1540 case RpcSecurity::TLS: {
1541 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1542 serverVersion);
1543 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1544 serverVersion);
1545 } break;
1546 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001547 }
1548 }
1549 }
1550 return ret;
1551 }
1552 template <typename A, typename B>
1553 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001554 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1555 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001556 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1557 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001558 void SetUp() override {
1559 if constexpr (!kEnableRpcThreads) {
1560 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1561 }
1562 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001563};
1564
1565TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001566 auto server = std::make_unique<Server>();
1567 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001568
1569 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001570 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001571
1572 ASSERT_EQ(OK, trust(&client, server));
1573 ASSERT_EQ(OK, trust(server, &client));
1574
1575 server->start();
1576 client.run();
1577}
1578
1579TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001580 auto server = std::make_unique<Server>();
1581 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001582
1583 std::vector<Client> clients;
1584 for (int i = 0; i < 2; i++) {
1585 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001586 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001587 ASSERT_EQ(OK, trust(&client, server));
1588 ASSERT_EQ(OK, trust(server, &client));
1589 }
1590
1591 server->start();
1592 for (auto& client : clients) client.run();
1593}
1594
1595TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001596 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1597 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001598
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001599 auto untrustedServer = std::make_unique<Server>();
1600 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001601
1602 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001603 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001604
1605 ASSERT_EQ(OK, trust(untrustedServer, &client));
1606
1607 untrustedServer->start();
1608
1609 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1610 // the client can't verify the server's identity.
1611 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1612 client.run(handshakeOk);
1613}
1614TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001615 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1616 (void)serverVersion;
1617
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001618 auto validServer = std::make_unique<Server>();
1619 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001621 auto maliciousServer = std::make_unique<Server>();
1622 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623
1624 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001625 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001626
1627 ASSERT_EQ(OK, trust(&client, validServer));
1628 ASSERT_EQ(OK, trust(validServer, &client));
1629 ASSERT_EQ(OK, trust(maliciousServer, &client));
1630
1631 maliciousServer->start();
1632
1633 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1634 // the client can't verify the server's identity.
1635 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1636 client.run(handshakeOk);
1637}
1638
1639TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001640 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1641 (void)serverVersion;
1642
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001643 auto server = std::make_unique<Server>();
1644 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001645
1646 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001647 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001648
1649 ASSERT_EQ(OK, trust(&client, server));
1650
1651 server->start();
1652
1653 // For TLS, Client should be able to verify server's identity, so client should see
1654 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1655 // identity and should drop the connection, so client shouldn't be able to read anything.
1656 bool readOk = rpcSecurity != RpcSecurity::TLS;
1657 client.run(true, readOk);
1658}
1659
1660TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001661 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1662 (void)serverVersion;
1663
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001664 auto server = std::make_unique<Server>();
1665 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001666
1667 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001668 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001669 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001670 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001671
1672 ASSERT_EQ(OK, trust(&validClient, server));
1673 ASSERT_EQ(OK, trust(&maliciousClient, server));
1674
1675 server->start();
1676
1677 // See UntrustedClient.
1678 bool readOk = rpcSecurity != RpcSecurity::TLS;
1679 maliciousClient.run(true, readOk);
1680}
1681
Yifan Hong67519322021-09-13 18:51:16 -07001682TEST_P(RpcTransportTest, Trigger) {
1683 std::string msg2 = ", world!";
1684 std::mutex writeMutex;
1685 std::condition_variable writeCv;
1686 bool shouldContinueWriting = false;
1687 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001688 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001689 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001690 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1691 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001692 if (status != OK) return AssertionFailure() << statusToString(status);
1693
1694 {
1695 std::unique_lock<std::mutex> lock(writeMutex);
1696 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1697 return AssertionFailure() << "write barrier not cleared in time!";
1698 }
1699 }
1700
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001701 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001702 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1703 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001704 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001705 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001706 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001707 << statusToString(status);
1708 return AssertionSuccess();
1709 };
1710
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001711 auto server = std::make_unique<Server>();
1712 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001713
1714 // Set up client
1715 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001716 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001717
1718 // Exchange keys
1719 ASSERT_EQ(OK, trust(&client, server));
1720 ASSERT_EQ(OK, trust(server, &client));
1721
1722 server->setPostConnect(serverPostConnect);
1723
Yifan Hong67519322021-09-13 18:51:16 -07001724 server->start();
1725 // connect() to server and do handshake
1726 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001727 // read the first message. This ensures that server has finished handshake and start handling
1728 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001729 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001730 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1731 // write is on an FdTrigger that has been shut down.
1732 server->shutdown();
1733 // Continues server thread to write the second message.
1734 {
Yifan Hong22211f82021-09-14 12:32:25 -07001735 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001736 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001737 }
Yifan Hong22211f82021-09-14 12:32:25 -07001738 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001739 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001740 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001741 // On the client side, second read fails with DEAD_OBJECT
1742 ASSERT_FALSE(client.readMessage(msg2));
1743}
1744
Pawan49d74cb2022-08-03 21:19:11 +00001745TEST_P(RpcTransportTest, CheckWaitingForRead) {
1746 std::mutex readMutex;
1747 std::condition_variable readCv;
1748 bool shouldContinueReading = false;
1749 // Server will write data on transport once its started
1750 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1751 std::string message(RpcTransportTestUtils::kMessage);
1752 iovec messageIov{message.data(), message.size()};
1753 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1754 std::nullopt, nullptr);
1755 if (status != OK) return AssertionFailure() << statusToString(status);
1756
1757 {
1758 std::unique_lock<std::mutex> lock(readMutex);
1759 shouldContinueReading = true;
1760 lock.unlock();
1761 readCv.notify_all();
1762 }
1763 return AssertionSuccess();
1764 };
1765
1766 // Setup Server and client
1767 auto server = std::make_unique<Server>();
1768 ASSERT_TRUE(server->setUp(GetParam()));
1769
1770 Client client(server->getConnectToServerFn());
1771 ASSERT_TRUE(client.setUp(GetParam()));
1772
1773 ASSERT_EQ(OK, trust(&client, server));
1774 ASSERT_EQ(OK, trust(server, &client));
1775 server->setPostConnect(serverPostConnect);
1776
1777 server->start();
1778 ASSERT_TRUE(client.setUpTransport());
1779 {
1780 // Wait till server writes data
1781 std::unique_lock<std::mutex> lock(readMutex);
1782 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1783 }
1784
1785 // Since there is no read polling here, we will get polling count 0
1786 ASSERT_FALSE(client.isTransportWaiting());
1787 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1788 // Thread should increment polling count, read and decrement polling count
1789 // Again, polling count should be zero here
1790 ASSERT_FALSE(client.isTransportWaiting());
1791
1792 server->shutdown();
1793}
1794
Yifan Hong1deca4b2021-09-10 16:16:44 -07001795INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001796 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001797 RpcTransportTest::PrintParamInfo);
1798
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001799class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001800 : public testing::TestWithParam<
1801 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001802public:
1803 template <typename A, typename B>
1804 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001805 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1806 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001807 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1808 }
1809 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001810 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1811 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1812 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001813 };
1814};
1815
1816TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001817 if constexpr (!kEnableRpcThreads) {
1818 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1819 }
1820
Frederick Mayledc07cf82022-05-26 20:30:12 +00001821 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001822
1823 std::vector<uint8_t> pkeyData, certData;
1824 {
1825 auto pkey = makeKeyPairForSelfSignedCert();
1826 ASSERT_NE(nullptr, pkey);
1827 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1828 ASSERT_NE(nullptr, cert);
1829 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1830 certData = serializeCertificate(cert.get(), certificateFormat);
1831 }
1832
1833 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1834 auto desCert = deserializeCertificate(certData, certificateFormat);
1835 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001836 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1837 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001838
1839 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1840 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1841
1842 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1843 ASSERT_TRUE(client.setUp(utilsParam));
1844
1845 ASSERT_EQ(OK, trust(&client, server));
1846 ASSERT_EQ(OK, trust(server, &client));
1847
1848 server->start();
1849 client.run();
1850}
1851
1852INSTANTIATE_TEST_CASE_P(
1853 BinderRpc, RpcTransportTlsKeyTest,
1854 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1855 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001856 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1857 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001858 RpcTransportTlsKeyTest::PrintParamInfo);
1859
Steven Morelandc1635952021-04-01 16:20:47 +00001860} // namespace android
1861
1862int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001863 ::testing::InitGoogleTest(&argc, argv);
1864 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001865
Steven Moreland5553ac42020-11-11 02:14:45 +00001866 return RUN_ALL_TESTS();
1867}