blob: 89526a6c7b9a07ccaf82c8ef011beff640b88241 [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 Wang893a9912022-10-24 10:44:09 +0000255 base::unique_fd bootstrapClientFd, bootstrapServerFd, socketFd;
Andrei Homescu96834632022-10-14 00:49:49 +0000256 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
257 // This is because we cannot pass ParcelFileDescriptor over a pipe.
258 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &bootstrapServerFd)) {
259 int savedErrno = errno;
260 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
Andrei Homescua858b0e2022-08-01 23:43:09 +0000261 }
Alice Wang893a9912022-10-24 10:44:09 +0000262 auto addr = allocateSocketAddress();
263 // Initializes the socket before the fork/exec.
264 if (socketType == SocketType::UNIX_RAW) {
265 socketFd = initUnixSocket(addr);
266 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000267
Andrei Homescu96834632022-10-14 00:49:49 +0000268 auto ret = std::make_unique<LinuxProcessSession>(
269 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
270 auto writeFd = std::to_string(writeEnd.get());
271 auto readFd = std::to_string(readEnd.get());
272 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
273 NULL);
274 }));
275
276 BinderRpcTestServerConfig serverConfig;
277 serverConfig.numThreads = options.numThreads;
278 serverConfig.socketType = static_cast<int32_t>(socketType);
279 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
280 serverConfig.serverVersion = serverVersion;
281 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000282 serverConfig.addr = addr;
Andrei Homescu96834632022-10-14 00:49:49 +0000283 serverConfig.unixBootstrapFd = bootstrapServerFd.get();
Alice Wang893a9912022-10-24 10:44:09 +0000284 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000285 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
286 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
287 static_cast<int32_t>(mode));
288 }
289 writeToFd(ret->host.writeEnd(), serverConfig);
290
291 std::vector<sp<RpcSession>> sessions;
292 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
293 for (size_t i = 0; i < options.numSessions; i++) {
294 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
David Brazdil21c887c2022-09-23 12:25:18 +0100295 }
296
Andrei Homescu96834632022-10-14 00:49:49 +0000297 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
298 BinderRpcTestClientInfo clientInfo;
299 for (const auto& session : sessions) {
300 auto& parcelableCert = clientInfo.certs.emplace_back();
301 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
302 }
303 writeToFd(ret->host.writeEnd(), clientInfo);
304
305 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
306 if (socketType == SocketType::INET) {
307 CHECK_NE(0, serverInfo.port);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000308 }
309
Andrei Homescu96834632022-10-14 00:49:49 +0000310 if (rpcSecurity == RpcSecurity::TLS) {
311 const auto& serverCert = serverInfo.cert.data;
312 CHECK_EQ(OK,
313 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700314 }
315
Andrei Homescu96834632022-10-14 00:49:49 +0000316 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000317
Andrei Homescu96834632022-10-14 00:49:49 +0000318 for (const auto& session : sessions) {
319 CHECK(session->setProtocolVersion(clientVersion));
320 session->setMaxIncomingThreads(options.numIncomingConnections);
321 session->setMaxOutgoingThreads(options.numOutgoingConnections);
322 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000323
Andrei Homescu96834632022-10-14 00:49:49 +0000324 switch (socketType) {
325 case SocketType::PRECONNECTED:
326 status = session->setupPreconnectedClient({}, [=]() {
327 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
328 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000329 break;
Alice Wang893a9912022-10-24 10:44:09 +0000330 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000331 case SocketType::UNIX:
332 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
333 break;
334 case SocketType::UNIX_BOOTSTRAP:
335 status = session->setupUnixDomainSocketBootstrapClient(
336 base::unique_fd(dup(bootstrapClientFd.get())));
337 break;
338 case SocketType::VSOCK:
339 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
340 break;
341 case SocketType::INET:
342 status = session->setupInetClient("127.0.0.1", serverInfo.port);
343 break;
344 default:
345 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000346 }
Andrei Homescu96834632022-10-14 00:49:49 +0000347 if (options.allowConnectFailure && status != OK) {
348 ret->sessions.clear();
349 break;
350 }
351 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
352 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000353 }
Andrei Homescu96834632022-10-14 00:49:49 +0000354 return ret;
355}
Steven Morelandc1635952021-04-01 16:20:47 +0000356
Andrei Homescua858b0e2022-08-01 23:43:09 +0000357TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
358 if (clientOrServerSingleThreaded()) {
359 GTEST_SKIP() << "This test requires multiple threads";
360 }
361
Steven Moreland5553ac42020-11-11 02:14:45 +0000362 constexpr size_t kNumThreads = 10;
363
Steven Moreland4313d7e2021-07-15 23:41:22 +0000364 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000365
366 EXPECT_OK(proc.rootIface->lock());
367
368 // block all but one thread taking locks
369 std::vector<std::thread> ts;
370 for (size_t i = 0; i < kNumThreads - 1; i++) {
371 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
372 }
373
Steven Morelanddd231e22022-09-08 19:47:49 +0000374 usleep(10000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000375
376 // other calls still work
377 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
378
Steven Morelanddd231e22022-09-08 19:47:49 +0000379 constexpr size_t blockTimeMs = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000380 size_t epochMsBefore = epochMillis();
381 // after this, we should never see a response within this time
382 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
383
384 // this call should be blocked for blockTimeMs
385 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
386
387 size_t epochMsAfter = epochMillis();
388 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
389
390 for (auto& t : ts) t.join();
391}
392
Andrei Homescu96834632022-10-14 00:49:49 +0000393static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
394 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000395 size_t epochMsBefore = epochMillis();
396
397 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700398 for (size_t i = 0; i < numCalls; i++) {
399 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000400 }
401
402 for (auto& t : ts) t.join();
403
404 size_t epochMsAfter = epochMillis();
405
Yifan Hong1f44f982021-10-08 17:16:47 -0700406 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000407
408 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700409 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
410}
411
Andrei Homescua858b0e2022-08-01 23:43:09 +0000412TEST_P(BinderRpc, ThreadPoolOverSaturated) {
413 if (clientOrServerSingleThreaded()) {
414 GTEST_SKIP() << "This test requires multiple threads";
415 }
416
Yifan Hong1f44f982021-10-08 17:16:47 -0700417 constexpr size_t kNumThreads = 10;
418 constexpr size_t kNumCalls = kNumThreads + 3;
419 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
420 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
421}
422
Andrei Homescua858b0e2022-08-01 23:43:09 +0000423TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
424 if (clientOrServerSingleThreaded()) {
425 GTEST_SKIP() << "This test requires multiple threads";
426 }
427
Yifan Hong1f44f982021-10-08 17:16:47 -0700428 constexpr size_t kNumThreads = 20;
429 constexpr size_t kNumOutgoingConnections = 10;
430 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
431 auto proc = createRpcTestSocketServerProcess(
432 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
433 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000434}
435
Andrei Homescua858b0e2022-08-01 23:43:09 +0000436TEST_P(BinderRpc, ThreadingStressTest) {
437 if (clientOrServerSingleThreaded()) {
438 GTEST_SKIP() << "This test requires multiple threads";
439 }
440
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 constexpr size_t kNumClientThreads = 10;
442 constexpr size_t kNumServerThreads = 10;
443 constexpr size_t kNumCalls = 100;
444
Steven Moreland4313d7e2021-07-15 23:41:22 +0000445 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000446
447 std::vector<std::thread> threads;
448 for (size_t i = 0; i < kNumClientThreads; i++) {
449 threads.push_back(std::thread([&] {
450 for (size_t j = 0; j < kNumCalls; j++) {
451 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000452 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000453 EXPECT_EQ(proc.rootBinder, out);
454 }
455 }));
456 }
457
458 for (auto& t : threads) t.join();
459}
460
Steven Moreland925ba0a2021-09-17 18:06:32 -0700461static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
462 std::vector<std::thread> threads;
463 for (size_t i = 0; i < threadCount; i++) {
464 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
465 }
466 for (auto& t : threads) t.join();
467}
468
Andrei Homescua858b0e2022-08-01 23:43:09 +0000469TEST_P(BinderRpc, OnewayStressTest) {
470 if (clientOrServerSingleThreaded()) {
471 GTEST_SKIP() << "This test requires multiple threads";
472 }
473
Steven Morelandc6046982021-04-20 00:49:42 +0000474 constexpr size_t kNumClientThreads = 10;
475 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700476 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000477
Steven Moreland4313d7e2021-07-15 23:41:22 +0000478 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000479
480 std::vector<std::thread> threads;
481 for (size_t i = 0; i < kNumClientThreads; i++) {
482 threads.push_back(std::thread([&] {
483 for (size_t j = 0; j < kNumCalls; j++) {
484 EXPECT_OK(proc.rootIface->sendString("a"));
485 }
Steven Morelandc6046982021-04-20 00:49:42 +0000486 }));
487 }
488
489 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700490
491 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000492}
493
Frederick Mayleb0221d12022-10-03 23:10:53 +0000494TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
495 if (!supportsFdTransport()) {
496 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
497 }
498 if (clientOrServerSingleThreaded()) {
499 GTEST_SKIP() << "This test requires multiple threads";
500 }
501
502 // This test forces a oneway transaction to be queued by issuing two
503 // `blockingSendFdOneway` calls, then drains the queue by issuing two
504 // `blockingRecvFd` calls.
505 //
506 // For more details about the queuing semantics see
507 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
508
509 auto proc = createRpcTestSocketServerProcess({
510 .numThreads = 3,
511 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
512 .serverSupportedFileDescriptorTransportModes =
513 {RpcSession::FileDescriptorTransportMode::UNIX},
514 });
515
516 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
517 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
518 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
519 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
520
521 android::os::ParcelFileDescriptor fdA;
522 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
523 std::string result;
524 CHECK(android::base::ReadFdToString(fdA.get(), &result));
525 EXPECT_EQ(result, "a");
526
527 android::os::ParcelFileDescriptor fdB;
528 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
529 CHECK(android::base::ReadFdToString(fdB.get(), &result));
530 EXPECT_EQ(result, "b");
531}
532
Andrei Homescua858b0e2022-08-01 23:43:09 +0000533TEST_P(BinderRpc, OnewayCallQueueing) {
534 if (clientOrServerSingleThreaded()) {
535 GTEST_SKIP() << "This test requires multiple threads";
536 }
537
Steven Moreland5553ac42020-11-11 02:14:45 +0000538 constexpr size_t kNumSleeps = 10;
539 constexpr size_t kNumExtraServerThreads = 4;
540 constexpr size_t kSleepMs = 50;
541
542 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000543 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000544
545 EXPECT_OK(proc.rootIface->lock());
546
Steven Moreland1c678802021-09-17 16:48:47 -0700547 size_t epochMsBefore = epochMillis();
548
549 // all these *Async commands should be queued on the server sequentially,
550 // even though there are multiple threads.
551 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 proc.rootIface->sleepMsAsync(kSleepMs);
553 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
555
Steven Moreland1c678802021-09-17 16:48:47 -0700556 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000557 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700558
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 size_t epochMsAfter = epochMillis();
560
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000561 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000562
Steven Moreland925ba0a2021-09-17 18:06:32 -0700563 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000564}
565
Andrei Homescua858b0e2022-08-01 23:43:09 +0000566TEST_P(BinderRpc, OnewayCallExhaustion) {
567 if (clientOrServerSingleThreaded()) {
568 GTEST_SKIP() << "This test requires multiple threads";
569 }
570
Steven Morelandd45be622021-06-04 02:19:37 +0000571 constexpr size_t kNumClients = 2;
572 constexpr size_t kTooLongMs = 1000;
573
Steven Moreland4313d7e2021-07-15 23:41:22 +0000574 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000575
576 // Build up oneway calls on the second session to make sure it terminates
577 // and shuts down. The first session should be unaffected (proc destructor
578 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000579 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000580
581 std::vector<std::thread> threads;
582 for (size_t i = 0; i < kNumClients; i++) {
583 // one of these threads will get stuck queueing a transaction once the
584 // socket fills up, the other will be able to fill up transactions on
585 // this object
586 threads.push_back(std::thread([&] {
587 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
588 }
589 }));
590 }
591 for (auto& t : threads) t.join();
592
593 Status status = iface->sleepMsAsync(kTooLongMs);
594 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
595
Steven Moreland798e0d12021-07-14 23:19:25 +0000596 // now that it has died, wait for the remote session to shutdown
597 std::vector<int32_t> remoteCounts;
598 do {
599 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
600 } while (remoteCounts.size() == kNumClients);
601
Steven Morelandd45be622021-06-04 02:19:37 +0000602 // the second session should be shutdown in the other process by the time we
603 // are able to join above (it'll only be hung up once it finishes processing
604 // any pending commands). We need to erase this session from the record
605 // here, so that the destructor for our session won't check that this
606 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000607 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000608}
609
Devin Moore66d5b7a2022-07-07 21:42:10 +0000610TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000611 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000612 GTEST_SKIP() << "This test requires multiple threads";
613 }
614 class MyDeathRec : public IBinder::DeathRecipient {
615 public:
616 void binderDied(const wp<IBinder>& /* who */) override {
617 dead = true;
618 mCv.notify_one();
619 }
620 std::mutex mMtx;
621 std::condition_variable mCv;
622 bool dead = false;
623 };
624
625 // Death recipient needs to have an incoming connection to be called
626 auto proc = createRpcTestSocketServerProcess(
627 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
628
629 auto dr = sp<MyDeathRec>::make();
630 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
631
632 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
633 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
634 }
635
636 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000637 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000638
639 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000640 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000641 proc.expectAlreadyShutdown = true;
642}
643
644TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000645 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000646 GTEST_SKIP() << "This test requires multiple threads";
647 }
648 class MyDeathRec : public IBinder::DeathRecipient {
649 public:
650 void binderDied(const wp<IBinder>& /* who */) override {
651 dead = true;
652 mCv.notify_one();
653 }
654 std::mutex mMtx;
655 std::condition_variable mCv;
656 bool dead = false;
657 };
658
659 // Death recipient needs to have an incoming connection to be called
660 auto proc = createRpcTestSocketServerProcess(
661 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
662
663 auto dr = sp<MyDeathRec>::make();
664 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
665
666 // Explicitly calling shutDownAndWait will cause the death recipients
667 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000668 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000669
670 std::unique_lock<std::mutex> lock(dr->mMtx);
671 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000672 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000673 }
674 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
675
Andrei Homescu96834632022-10-14 00:49:49 +0000676 proc.proc->terminate();
677 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000678 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
679 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
680 });
681 proc.expectAlreadyShutdown = true;
682}
683
684TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
685 class MyDeathRec : public IBinder::DeathRecipient {
686 public:
687 void binderDied(const wp<IBinder>& /* who */) override {}
688 };
689
690 auto proc = createRpcTestSocketServerProcess(
691 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
692
693 auto dr = sp<MyDeathRec>::make();
694 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
695 "Cannot register a DeathRecipient without any incoming connections.");
696}
697
698TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000699 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000700 GTEST_SKIP() << "This test requires multiple threads";
701 }
702 class MyDeathRec : public IBinder::DeathRecipient {
703 public:
704 void binderDied(const wp<IBinder>& /* who */) override {
705 GTEST_FAIL() << "This should not be called after unlinkToDeath";
706 }
707 };
708
709 // Death recipient needs to have an incoming connection to be called
710 auto proc = createRpcTestSocketServerProcess(
711 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
712
713 auto dr = sp<MyDeathRec>::make();
714 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
715 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
716
717 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
718 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
719 }
720
721 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000722 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000723 proc.expectAlreadyShutdown = true;
724}
725
Steven Morelandc1635952021-04-01 16:20:47 +0000726TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000727 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000728 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000729
730 // make sure there is some state during crash
731 // 1. we hold their binder
732 sp<IBinderRpcSession> session;
733 EXPECT_OK(proc.rootIface->openSession("happy", &session));
734 // 2. they hold our binder
735 sp<IBinder> binder = new BBinder();
736 EXPECT_OK(proc.rootIface->holdBinder(binder));
737
738 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
739 << "Do death cleanup: " << doDeathCleanup;
740
Andrei Homescu96834632022-10-14 00:49:49 +0000741 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000742 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
743 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
744 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000745 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000746 }
747}
748
Steven Morelandd7302072021-05-15 01:32:04 +0000749TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000750 // This test only works if the current process shared the internal state of
751 // ProcessState with the service across the call to fork(). Both the static
752 // libraries and libbinder.so have their own separate copies of all the
753 // globals, so the test only works when the test client and service both use
754 // libbinder.so (when using static libraries, even a client and service
755 // using the same kind of static library should have separate copies of the
756 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000757 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000758 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
759 "at build time.";
760 }
761
Steven Moreland4313d7e2021-07-15 23:41:22 +0000762 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000763
Andrei Homescu2a298012022-06-15 01:08:54 +0000764 // we can't allocate IPCThreadState so actually the first time should
765 // succeed :(
766 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000767
768 // second time! we catch the error :)
769 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
770
Andrei Homescu96834632022-10-14 00:49:49 +0000771 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000772 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
773 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
774 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000775 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000776}
777
Frederick Mayle69a0c992022-05-26 20:38:39 +0000778TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
779 auto proc = createRpcTestSocketServerProcess({
780 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
781 .serverSupportedFileDescriptorTransportModes =
782 {RpcSession::FileDescriptorTransportMode::UNIX},
783 .allowConnectFailure = true,
784 });
Andrei Homescu96834632022-10-14 00:49:49 +0000785 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
786 proc.proc->terminate();
787 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000788 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
789 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
790 });
791 proc.expectAlreadyShutdown = true;
792}
793
794TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
795 auto proc = createRpcTestSocketServerProcess({
796 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
797 .serverSupportedFileDescriptorTransportModes =
798 {RpcSession::FileDescriptorTransportMode::NONE},
799 .allowConnectFailure = true,
800 });
Andrei Homescu96834632022-10-14 00:49:49 +0000801 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
802 proc.proc->terminate();
803 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000804 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
805 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
806 });
807 proc.expectAlreadyShutdown = true;
808}
809
810TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
811 auto proc = createRpcTestSocketServerProcess({
812 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
813 .serverSupportedFileDescriptorTransportModes =
814 {RpcSession::FileDescriptorTransportMode::NONE,
815 RpcSession::FileDescriptorTransportMode::UNIX},
816 });
817
818 android::os::ParcelFileDescriptor out;
819 auto status = proc.rootIface->echoAsFile("hello", &out);
820 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
821}
822
823TEST_P(BinderRpc, ReceiveFile) {
824 auto proc = createRpcTestSocketServerProcess({
825 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
826 .serverSupportedFileDescriptorTransportModes =
827 {RpcSession::FileDescriptorTransportMode::UNIX},
828 });
829
830 android::os::ParcelFileDescriptor out;
831 auto status = proc.rootIface->echoAsFile("hello", &out);
832 if (!supportsFdTransport()) {
833 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
834 return;
835 }
836 ASSERT_TRUE(status.isOk()) << status;
837
838 std::string result;
839 CHECK(android::base::ReadFdToString(out.get(), &result));
840 EXPECT_EQ(result, "hello");
841}
842
843TEST_P(BinderRpc, SendFiles) {
844 auto proc = createRpcTestSocketServerProcess({
845 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
846 .serverSupportedFileDescriptorTransportModes =
847 {RpcSession::FileDescriptorTransportMode::UNIX},
848 });
849
850 std::vector<android::os::ParcelFileDescriptor> files;
851 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
852 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
853 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
854 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
855
856 android::os::ParcelFileDescriptor out;
857 auto status = proc.rootIface->concatFiles(files, &out);
858 if (!supportsFdTransport()) {
859 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
860 return;
861 }
862 ASSERT_TRUE(status.isOk()) << status;
863
864 std::string result;
865 CHECK(android::base::ReadFdToString(out.get(), &result));
866 EXPECT_EQ(result, "123abcd");
867}
868
869TEST_P(BinderRpc, SendMaxFiles) {
870 if (!supportsFdTransport()) {
871 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
872 }
873
874 auto proc = createRpcTestSocketServerProcess({
875 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
876 .serverSupportedFileDescriptorTransportModes =
877 {RpcSession::FileDescriptorTransportMode::UNIX},
878 });
879
880 std::vector<android::os::ParcelFileDescriptor> files;
881 for (int i = 0; i < 253; i++) {
882 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
883 }
884
885 android::os::ParcelFileDescriptor out;
886 auto status = proc.rootIface->concatFiles(files, &out);
887 ASSERT_TRUE(status.isOk()) << status;
888
889 std::string result;
890 CHECK(android::base::ReadFdToString(out.get(), &result));
891 EXPECT_EQ(result, std::string(253, 'a'));
892}
893
894TEST_P(BinderRpc, SendTooManyFiles) {
895 if (!supportsFdTransport()) {
896 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
897 }
898
899 auto proc = createRpcTestSocketServerProcess({
900 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
901 .serverSupportedFileDescriptorTransportModes =
902 {RpcSession::FileDescriptorTransportMode::UNIX},
903 });
904
905 std::vector<android::os::ParcelFileDescriptor> files;
906 for (int i = 0; i < 254; i++) {
907 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
908 }
909
910 android::os::ParcelFileDescriptor out;
911 auto status = proc.rootIface->concatFiles(files, &out);
912 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
913}
914
Andrei Homescufc221502022-10-08 03:51:17 +0000915TEST_P(BinderRpc, AppendInvalidFd) {
916 auto proc = createRpcTestSocketServerProcess({
917 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
918 .serverSupportedFileDescriptorTransportModes =
919 {RpcSession::FileDescriptorTransportMode::UNIX},
920 });
921
922 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
923 ASSERT_NE(badFd, -1);
924
925 // Close the file descriptor so it becomes invalid for dup
926 close(badFd);
927
928 Parcel p1;
929 p1.markForBinder(proc.rootBinder);
930 p1.writeInt32(3);
931 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
932
933 Parcel pRaw;
934 pRaw.markForBinder(proc.rootBinder);
935 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
936
937 pRaw.setDataPosition(0);
938 EXPECT_EQ(3, pRaw.readInt32());
939 ASSERT_EQ(-1, pRaw.readFileDescriptor());
940}
941
Steven Moreland37aff182021-03-26 02:04:16 +0000942TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000943 if constexpr (!kEnableSharedLibs) {
944 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
945 }
946
Steven Moreland4313d7e2021-07-15 23:41:22 +0000947 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000948
949 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
950 ASSERT_NE(binder, nullptr);
951
952 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
953}
954
955TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000956 if constexpr (!kEnableSharedLibs) {
957 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
958 }
959
Steven Moreland4313d7e2021-07-15 23:41:22 +0000960 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000961
962 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
963 ASSERT_NE(binder, nullptr);
964
965 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
966 ASSERT_NE(ndkBinder, nullptr);
967
968 std::string out;
969 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
970 ASSERT_TRUE(status.isOk()) << status.getDescription();
971 ASSERT_EQ("aoeuaoeu", out);
972}
973
Steven Moreland5553ac42020-11-11 02:14:45 +0000974ssize_t countFds() {
975 DIR* dir = opendir("/proc/self/fd/");
976 if (dir == nullptr) return -1;
977 ssize_t ret = 0;
978 dirent* ent;
979 while ((ent = readdir(dir)) != nullptr) ret++;
980 closedir(dir);
981 return ret;
982}
983
Andrei Homescua858b0e2022-08-01 23:43:09 +0000984TEST_P(BinderRpc, Fds) {
985 if (serverSingleThreaded()) {
986 GTEST_SKIP() << "This test requires multiple threads";
987 }
988
Steven Moreland5553ac42020-11-11 02:14:45 +0000989 ssize_t beforeFds = countFds();
990 ASSERT_GE(beforeFds, 0);
991 {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +0000993 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
994 }
995 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
996}
997
Steven Morelandda573042021-06-12 01:13:45 +0000998static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -0700999 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001000 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001001
Andrei Homescu992a4052022-06-28 21:26:18 +00001002 android::base::unique_fd serverFd(
1003 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1004 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1005
1006 sockaddr_vm serverAddr{
1007 .svm_family = AF_VSOCK,
1008 .svm_port = vsockPort,
1009 .svm_cid = VMADDR_CID_ANY,
1010 };
1011 int ret = TEMP_FAILURE_RETRY(
1012 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1013 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1014 strerror(errno));
1015
1016 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1017 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1018 strerror(errno));
1019
1020 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1021 // to see if the kernel supports it. It's safe to use a blocking
1022 // connect because vsock sockets have a 2 second connection timeout,
1023 // and they return ETIMEDOUT after that.
1024 android::base::unique_fd connectFd(
1025 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1026 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1027 strerror(errno));
1028
1029 bool success = false;
1030 sockaddr_vm connectAddr{
1031 .svm_family = AF_VSOCK,
1032 .svm_port = vsockPort,
1033 .svm_cid = VMADDR_CID_LOCAL,
1034 };
1035 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1036 sizeof(connectAddr)));
1037 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1038 android::base::unique_fd acceptFd;
1039 while (true) {
1040 pollfd pfd[]{
1041 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1042 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1043 };
1044 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1045 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1046
1047 if (pfd[0].revents & POLLIN) {
1048 sockaddr_vm acceptAddr;
1049 socklen_t acceptAddrLen = sizeof(acceptAddr);
1050 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1051 reinterpret_cast<sockaddr*>(&acceptAddr),
1052 &acceptAddrLen, SOCK_CLOEXEC));
1053 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1054 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1055 "Truncated address");
1056
1057 // Store the fd in acceptFd so we keep the connection alive
1058 // while polling connectFd
1059 acceptFd.reset(ret);
1060 }
1061
1062 if (pfd[1].revents & POLLOUT) {
1063 // Connect either succeeded or timed out
1064 int connectErrno;
1065 socklen_t connectErrnoLen = sizeof(connectErrno);
1066 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1067 &connectErrnoLen);
1068 LOG_ALWAYS_FATAL_IF(ret == -1,
1069 "Could not getsockopt() after connect() "
1070 "on non-blocking socket: %s.",
1071 strerror(errno));
1072
1073 // We're done, this is all we wanted
1074 success = connectErrno == 0;
1075 break;
1076 }
1077 }
1078 } else {
1079 success = ret == 0;
1080 }
1081
1082 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1083
1084 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001085}
1086
Yifan Hong1deca4b2021-09-10 16:16:44 -07001087static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001088 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1089 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001090
1091 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001092
1093 static bool hasVsockLoopback = testSupportVsockLoopback();
1094
1095 if (hasVsockLoopback) {
1096 ret.push_back(SocketType::VSOCK);
1097 }
1098
1099 return ret;
1100}
1101
Frederick Mayledc07cf82022-05-26 20:30:12 +00001102static std::vector<uint32_t> testVersions() {
1103 std::vector<uint32_t> versions;
1104 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1105 versions.push_back(i);
1106 }
1107 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1108 return versions;
1109}
1110
Yifan Hong702115c2021-06-24 15:39:18 -07001111INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1112 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001113 ::testing::ValuesIn(RpcSecurityValues()),
1114 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001115 ::testing::ValuesIn(testVersions()),
1116 ::testing::Values(false, true),
1117 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001118 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001119
Yifan Hong702115c2021-06-24 15:39:18 -07001120class BinderRpcServerRootObject
1121 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001122
1123TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1124 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1125 auto setRootObject = [](bool isStrong) -> SetFn {
1126 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1127 };
1128
Yifan Hong702115c2021-06-24 15:39:18 -07001129 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1130 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001131 auto binder1 = sp<BBinder>::make();
1132 IBinder* binderRaw1 = binder1.get();
1133 setRootObject(isStrong1)(server.get(), binder1);
1134 EXPECT_EQ(binderRaw1, server->getRootObject());
1135 binder1.clear();
1136 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1137
1138 auto binder2 = sp<BBinder>::make();
1139 IBinder* binderRaw2 = binder2.get();
1140 setRootObject(isStrong2)(server.get(), binder2);
1141 EXPECT_EQ(binderRaw2, server->getRootObject());
1142 binder2.clear();
1143 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1144}
1145
1146INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001147 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1148 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001149
Yifan Hong1a235852021-05-13 16:07:47 -07001150class OneOffSignal {
1151public:
1152 // If notify() was previously called, or is called within |duration|, return true; else false.
1153 template <typename R, typename P>
1154 bool wait(std::chrono::duration<R, P> duration) {
1155 std::unique_lock<std::mutex> lock(mMutex);
1156 return mCv.wait_for(lock, duration, [this] { return mValue; });
1157 }
1158 void notify() {
1159 std::unique_lock<std::mutex> lock(mMutex);
1160 mValue = true;
1161 lock.unlock();
1162 mCv.notify_all();
1163 }
1164
1165private:
1166 std::mutex mMutex;
1167 std::condition_variable mCv;
1168 bool mValue = false;
1169};
1170
Yifan Hong194acf22021-06-29 18:44:56 -07001171TEST(BinderRpc, Java) {
1172#if !defined(__ANDROID__)
1173 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1174 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1175 "to binderHostDeviceTest. Hence, just disable this test on host.";
1176#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001177 if constexpr (!kEnableKernelIpc) {
1178 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1179 "at build time.";
1180 }
1181
Yifan Hong194acf22021-06-29 18:44:56 -07001182 sp<IServiceManager> sm = defaultServiceManager();
1183 ASSERT_NE(nullptr, sm);
1184 // Any Java service with non-empty getInterfaceDescriptor() would do.
1185 // Let's pick batteryproperties.
1186 auto binder = sm->checkService(String16("batteryproperties"));
1187 ASSERT_NE(nullptr, binder);
1188 auto descriptor = binder->getInterfaceDescriptor();
1189 ASSERT_GE(descriptor.size(), 0);
1190 ASSERT_EQ(OK, binder->pingBinder());
1191
1192 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001193 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001194 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001195 auto socket = rpcServer->releaseServer();
1196
1197 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001198 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1199
Yifan Honge3caaf22022-01-12 14:46:56 -08001200 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1201 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001202 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001203 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1204 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001205 << statusToString(setRpcClientDebugStatus);
1206 GTEST_SKIP();
1207 }
1208
1209 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001210
1211 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001212 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001213 auto rpcBinder = rpcSession->getRootObject();
1214 ASSERT_NE(nullptr, rpcBinder);
1215
1216 ASSERT_EQ(OK, rpcBinder->pingBinder());
1217
1218 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1219 << "getInterfaceDescriptor should not crash system_server";
1220 ASSERT_EQ(OK, rpcBinder->pingBinder());
1221}
1222
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001223class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1224public:
1225 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1226 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1227 std::to_string(std::get<1>(info.param));
1228 }
1229};
1230
1231TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1232 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1233 int sinkFd = sink.get();
1234 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1235 server->setProtocolVersion(std::get<1>(GetParam()));
1236 ASSERT_FALSE(server->hasServer());
1237 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1238 ASSERT_TRUE(server->hasServer());
1239 base::unique_fd retrieved = server->releaseServer();
1240 ASSERT_FALSE(server->hasServer());
1241 ASSERT_EQ(sinkFd, retrieved.get());
1242}
1243
1244TEST_P(BinderRpcServerOnly, Shutdown) {
1245 if constexpr (!kEnableRpcThreads) {
1246 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1247 }
1248
1249 auto addr = allocateSocketAddress();
1250 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1251 server->setProtocolVersion(std::get<1>(GetParam()));
1252 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1253 auto joinEnds = std::make_shared<OneOffSignal>();
1254
1255 // If things are broken and the thread never stops, don't block other tests. Because the thread
1256 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1257 // shared pointers are passed.
1258 std::thread([server, joinEnds] {
1259 server->join();
1260 joinEnds->notify();
1261 }).detach();
1262
1263 bool shutdown = false;
1264 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001265 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001266 if (server->shutdown()) shutdown = true;
1267 }
1268 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1269
1270 ASSERT_TRUE(joinEnds->wait(2s))
1271 << "After server->shutdown() returns true, join() did not stop after 2s";
1272}
1273
Frederick Mayledc07cf82022-05-26 20:30:12 +00001274INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1275 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1276 ::testing::ValuesIn(testVersions())),
1277 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001278
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001279class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001280public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001281 // Only parameterized only server version because `RpcSession` is bypassed
1282 // in the client half of the tests.
1283 using Param =
1284 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001285 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001286
1287 // A server that handles client socket connections.
1288 class Server {
1289 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001290 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1291
Yifan Hong1deca4b2021-09-10 16:16:44 -07001292 explicit Server() {}
1293 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001294 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001295 [[nodiscard]] AssertionResult setUp(
1296 const Param& param,
1297 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001298 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001299 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001300 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001301 switch (socketType) {
1302 case SocketType::PRECONNECTED: {
1303 return AssertionFailure() << "Not supported by this test";
1304 } break;
1305 case SocketType::UNIX: {
1306 auto addr = allocateSocketAddress();
1307 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1308 if (status != OK) {
1309 return AssertionFailure()
1310 << "setupUnixDomainServer: " << statusToString(status);
1311 }
1312 mConnectToServer = [addr] {
1313 return connectTo(UnixSocketAddress(addr.c_str()));
1314 };
1315 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001316 case SocketType::UNIX_BOOTSTRAP: {
1317 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1318 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1319 return AssertionFailure() << "Socketpair() failed";
1320 }
1321 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1322 std::move(bootstrapFdServer));
1323 if (status != OK) {
1324 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1325 << statusToString(status);
1326 }
1327 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1328 mAcceptConnection = &Server::recvmsgServerConnection;
1329 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1330 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001331 case SocketType::UNIX_RAW: {
1332 auto addr = allocateSocketAddress();
1333 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1334 if (status != OK) {
1335 return AssertionFailure()
1336 << "setupRawSocketServer: " << statusToString(status);
1337 }
1338 mConnectToServer = [addr] {
1339 return connectTo(UnixSocketAddress(addr.c_str()));
1340 };
1341 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001342 case SocketType::VSOCK: {
1343 auto port = allocateVsockPort();
1344 auto status = rpcServer->setupVsockServer(port);
1345 if (status != OK) {
1346 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1347 }
1348 mConnectToServer = [port] {
1349 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1350 };
1351 } break;
1352 case SocketType::INET: {
1353 unsigned int port;
1354 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1355 if (status != OK) {
1356 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1357 }
1358 mConnectToServer = [port] {
1359 const char* addr = kLocalInetAddress;
1360 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1361 if (aiStart == nullptr) return base::unique_fd{};
1362 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1363 auto fd = connectTo(
1364 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1365 if (fd.ok()) return fd;
1366 }
1367 ALOGE("None of the socket address resolved for %s:%u can be connected",
1368 addr, port);
1369 return base::unique_fd{};
1370 };
1371 }
1372 }
1373 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001374 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001375 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001376 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1377 mSetup = true;
1378 return AssertionSuccess();
1379 }
1380 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1381 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1382 return mCertVerifier;
1383 }
1384 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1385 void start() {
1386 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1387 mThread = std::make_unique<std::thread>(&Server::run, this);
1388 }
David Brazdil21c887c2022-09-23 12:25:18 +01001389
1390 base::unique_fd acceptServerConnection() {
1391 return base::unique_fd(TEMP_FAILURE_RETRY(
1392 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1393 }
1394
1395 base::unique_fd recvmsgServerConnection() {
1396 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1397 int buf;
1398 iovec iov{&buf, sizeof(buf)};
1399
1400 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1401 int savedErrno = errno;
1402 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1403 }
1404 if (fds.size() != 1) {
1405 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1406 }
1407 return std::move(std::get<base::unique_fd>(fds[0]));
1408 }
1409
Yifan Hong1deca4b2021-09-10 16:16:44 -07001410 void run() {
1411 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1412
1413 std::vector<std::thread> threads;
1414 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001415 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001416 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1417 }
1418
1419 for (auto& thread : threads) thread.join();
1420 }
1421 void handleOne(android::base::unique_fd acceptedFd) {
1422 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001423 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001424 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001425 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001426 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001427 }
Yifan Honge07d2732021-09-13 21:59:14 -07001428 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001429 shutdown();
1430 join();
1431 }
1432 void shutdown() { mFdTrigger->trigger(); }
1433
1434 void setPostConnect(
1435 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1436 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001437 }
1438
1439 private:
1440 std::unique_ptr<std::thread> mThread;
1441 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001442 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001443 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001444 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001445 std::unique_ptr<RpcTransportCtx> mCtx;
1446 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1447 std::make_shared<RpcCertificateVerifierSimple>();
1448 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001449 // The function invoked after connection and handshake. By default, it is
1450 // |defaultPostConnect| that sends |kMessage| to the client.
1451 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1452 Server::defaultPostConnect;
1453
1454 void join() {
1455 if (mThread != nullptr) {
1456 mThread->join();
1457 mThread = nullptr;
1458 }
1459 }
1460
1461 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1462 FdTrigger* fdTrigger) {
1463 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001464 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001465 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001466 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001467 if (status != OK) return AssertionFailure() << statusToString(status);
1468 return AssertionSuccess();
1469 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001470 };
1471
1472 class Client {
1473 public:
1474 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1475 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001476 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001477 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1478 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001479 mFdTrigger = FdTrigger::make();
1480 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1481 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1482 return AssertionSuccess();
1483 }
1484 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1485 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1486 return mCertVerifier;
1487 }
Yifan Hong67519322021-09-13 18:51:16 -07001488 // connect() and do handshake
1489 bool setUpTransport() {
1490 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001491 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001492 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1493 return mClientTransport != nullptr;
1494 }
1495 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1496 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1497 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001498 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001499 status_t readStatus =
1500 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001501 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001502 if (readStatus != OK) {
1503 return AssertionFailure() << statusToString(readStatus);
1504 }
1505 if (readMessage != expectedMessage) {
1506 return AssertionFailure()
1507 << "Expected " << expectedMessage << ", actual " << readMessage;
1508 }
1509 return AssertionSuccess();
1510 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001511 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001512 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001513 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1514 return;
1515 }
1516 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001517 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001518 }
1519
Pawan49d74cb2022-08-03 21:19:11 +00001520 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1521
Yifan Hong1deca4b2021-09-10 16:16:44 -07001522 private:
1523 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001524 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001525 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1526 std::unique_ptr<RpcTransportCtx> mCtx;
1527 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1528 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001529 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001530 };
1531
1532 // Make A trust B.
1533 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001534 static status_t trust(RpcSecurity rpcSecurity,
1535 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1536 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001537 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001538 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1539 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1540 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001541 }
1542
1543 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001544};
1545
1546class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1547public:
1548 using Server = RpcTransportTestUtils::Server;
1549 using Client = RpcTransportTestUtils::Client;
1550 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001551 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001552 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1553 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001554 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001555 return ret;
1556 }
1557 static std::vector<ParamType> getRpcTranportTestParams() {
1558 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001559 for (auto serverVersion : testVersions()) {
1560 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1561 for (auto rpcSecurity : RpcSecurityValues()) {
1562 switch (rpcSecurity) {
1563 case RpcSecurity::RAW: {
1564 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1565 } break;
1566 case RpcSecurity::TLS: {
1567 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1568 serverVersion);
1569 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1570 serverVersion);
1571 } break;
1572 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001573 }
1574 }
1575 }
1576 return ret;
1577 }
1578 template <typename A, typename B>
1579 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001580 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1581 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001582 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1583 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001584 void SetUp() override {
1585 if constexpr (!kEnableRpcThreads) {
1586 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1587 }
1588 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001589};
1590
1591TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001592 auto server = std::make_unique<Server>();
1593 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001594
1595 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001596 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001597
1598 ASSERT_EQ(OK, trust(&client, server));
1599 ASSERT_EQ(OK, trust(server, &client));
1600
1601 server->start();
1602 client.run();
1603}
1604
1605TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001606 auto server = std::make_unique<Server>();
1607 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001608
1609 std::vector<Client> clients;
1610 for (int i = 0; i < 2; i++) {
1611 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001612 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001613 ASSERT_EQ(OK, trust(&client, server));
1614 ASSERT_EQ(OK, trust(server, &client));
1615 }
1616
1617 server->start();
1618 for (auto& client : clients) client.run();
1619}
1620
1621TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001622 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1623 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001624
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001625 auto untrustedServer = std::make_unique<Server>();
1626 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001627
1628 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001629 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630
1631 ASSERT_EQ(OK, trust(untrustedServer, &client));
1632
1633 untrustedServer->start();
1634
1635 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1636 // the client can't verify the server's identity.
1637 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1638 client.run(handshakeOk);
1639}
1640TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001641 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1642 (void)serverVersion;
1643
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001644 auto validServer = std::make_unique<Server>();
1645 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001646
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001647 auto maliciousServer = std::make_unique<Server>();
1648 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001649
1650 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001651 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001652
1653 ASSERT_EQ(OK, trust(&client, validServer));
1654 ASSERT_EQ(OK, trust(validServer, &client));
1655 ASSERT_EQ(OK, trust(maliciousServer, &client));
1656
1657 maliciousServer->start();
1658
1659 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1660 // the client can't verify the server's identity.
1661 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1662 client.run(handshakeOk);
1663}
1664
1665TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001666 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1667 (void)serverVersion;
1668
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001669 auto server = std::make_unique<Server>();
1670 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001671
1672 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001673 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001674
1675 ASSERT_EQ(OK, trust(&client, server));
1676
1677 server->start();
1678
1679 // For TLS, Client should be able to verify server's identity, so client should see
1680 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1681 // identity and should drop the connection, so client shouldn't be able to read anything.
1682 bool readOk = rpcSecurity != RpcSecurity::TLS;
1683 client.run(true, readOk);
1684}
1685
1686TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001687 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1688 (void)serverVersion;
1689
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001690 auto server = std::make_unique<Server>();
1691 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001692
1693 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001694 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001695 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001696 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001697
1698 ASSERT_EQ(OK, trust(&validClient, server));
1699 ASSERT_EQ(OK, trust(&maliciousClient, server));
1700
1701 server->start();
1702
1703 // See UntrustedClient.
1704 bool readOk = rpcSecurity != RpcSecurity::TLS;
1705 maliciousClient.run(true, readOk);
1706}
1707
Yifan Hong67519322021-09-13 18:51:16 -07001708TEST_P(RpcTransportTest, Trigger) {
1709 std::string msg2 = ", world!";
1710 std::mutex writeMutex;
1711 std::condition_variable writeCv;
1712 bool shouldContinueWriting = false;
1713 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001714 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001715 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001716 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1717 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001718 if (status != OK) return AssertionFailure() << statusToString(status);
1719
1720 {
1721 std::unique_lock<std::mutex> lock(writeMutex);
1722 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1723 return AssertionFailure() << "write barrier not cleared in time!";
1724 }
1725 }
1726
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001727 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001728 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1729 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001730 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001731 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001732 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001733 << statusToString(status);
1734 return AssertionSuccess();
1735 };
1736
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001737 auto server = std::make_unique<Server>();
1738 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001739
1740 // Set up client
1741 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001742 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001743
1744 // Exchange keys
1745 ASSERT_EQ(OK, trust(&client, server));
1746 ASSERT_EQ(OK, trust(server, &client));
1747
1748 server->setPostConnect(serverPostConnect);
1749
Yifan Hong67519322021-09-13 18:51:16 -07001750 server->start();
1751 // connect() to server and do handshake
1752 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001753 // read the first message. This ensures that server has finished handshake and start handling
1754 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001755 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001756 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1757 // write is on an FdTrigger that has been shut down.
1758 server->shutdown();
1759 // Continues server thread to write the second message.
1760 {
Yifan Hong22211f82021-09-14 12:32:25 -07001761 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001762 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001763 }
Yifan Hong22211f82021-09-14 12:32:25 -07001764 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001765 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001766 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001767 // On the client side, second read fails with DEAD_OBJECT
1768 ASSERT_FALSE(client.readMessage(msg2));
1769}
1770
Pawan49d74cb2022-08-03 21:19:11 +00001771TEST_P(RpcTransportTest, CheckWaitingForRead) {
1772 std::mutex readMutex;
1773 std::condition_variable readCv;
1774 bool shouldContinueReading = false;
1775 // Server will write data on transport once its started
1776 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1777 std::string message(RpcTransportTestUtils::kMessage);
1778 iovec messageIov{message.data(), message.size()};
1779 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1780 std::nullopt, nullptr);
1781 if (status != OK) return AssertionFailure() << statusToString(status);
1782
1783 {
1784 std::unique_lock<std::mutex> lock(readMutex);
1785 shouldContinueReading = true;
1786 lock.unlock();
1787 readCv.notify_all();
1788 }
1789 return AssertionSuccess();
1790 };
1791
1792 // Setup Server and client
1793 auto server = std::make_unique<Server>();
1794 ASSERT_TRUE(server->setUp(GetParam()));
1795
1796 Client client(server->getConnectToServerFn());
1797 ASSERT_TRUE(client.setUp(GetParam()));
1798
1799 ASSERT_EQ(OK, trust(&client, server));
1800 ASSERT_EQ(OK, trust(server, &client));
1801 server->setPostConnect(serverPostConnect);
1802
1803 server->start();
1804 ASSERT_TRUE(client.setUpTransport());
1805 {
1806 // Wait till server writes data
1807 std::unique_lock<std::mutex> lock(readMutex);
1808 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1809 }
1810
1811 // Since there is no read polling here, we will get polling count 0
1812 ASSERT_FALSE(client.isTransportWaiting());
1813 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1814 // Thread should increment polling count, read and decrement polling count
1815 // Again, polling count should be zero here
1816 ASSERT_FALSE(client.isTransportWaiting());
1817
1818 server->shutdown();
1819}
1820
Yifan Hong1deca4b2021-09-10 16:16:44 -07001821INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001822 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001823 RpcTransportTest::PrintParamInfo);
1824
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001825class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001826 : public testing::TestWithParam<
1827 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001828public:
1829 template <typename A, typename B>
1830 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001831 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1832 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001833 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1834 }
1835 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001836 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1837 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1838 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 };
1840};
1841
1842TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001843 if constexpr (!kEnableRpcThreads) {
1844 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1845 }
1846
Frederick Mayledc07cf82022-05-26 20:30:12 +00001847 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848
1849 std::vector<uint8_t> pkeyData, certData;
1850 {
1851 auto pkey = makeKeyPairForSelfSignedCert();
1852 ASSERT_NE(nullptr, pkey);
1853 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1854 ASSERT_NE(nullptr, cert);
1855 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1856 certData = serializeCertificate(cert.get(), certificateFormat);
1857 }
1858
1859 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1860 auto desCert = deserializeCertificate(certData, certificateFormat);
1861 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001862 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1863 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001864
1865 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1866 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1867
1868 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1869 ASSERT_TRUE(client.setUp(utilsParam));
1870
1871 ASSERT_EQ(OK, trust(&client, server));
1872 ASSERT_EQ(OK, trust(server, &client));
1873
1874 server->start();
1875 client.run();
1876}
1877
1878INSTANTIATE_TEST_CASE_P(
1879 BinderRpc, RpcTransportTlsKeyTest,
1880 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1881 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001882 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1883 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001884 RpcTransportTlsKeyTest::PrintParamInfo);
1885
Steven Morelandc1635952021-04-01 16:20:47 +00001886} // namespace android
1887
1888int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001889 ::testing::InitGoogleTest(&argc, argv);
1890 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001891
Steven Moreland5553ac42020-11-11 02:14:45 +00001892 return RUN_ALL_TESTS();
1893}