blob: 004dea317dd7eaea8e17e803005aba4119c3c2be [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
Andrei Homescu96834632022-10-14 00:49:49 +0000132// Destructors need to be defined, even if pure virtual
133ProcessSession::~ProcessSession() {}
134
135class LinuxProcessSession : public ProcessSession {
136public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 // reference to process hosting a socket server
138 Process host;
139
Andrei Homescu96834632022-10-14 00:49:49 +0000140 LinuxProcessSession(LinuxProcessSession&&) = default;
141 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
142 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000143 for (auto& session : sessions) {
144 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000145 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000146
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000147 for (auto& info : sessions) {
148 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000149
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000150 EXPECT_NE(nullptr, session);
151 EXPECT_NE(nullptr, session->state());
152 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000153
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 wp<RpcSession> weakSession = session;
155 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000156
Steven Moreland57042712022-10-04 23:56:45 +0000157 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
158 // the object should not actually be promotable. By looping, we distinguish a race here
159 // from a bug causing the object to not be promotable.
160 for (size_t i = 0; i < 3; i++) {
161 sp<RpcSession> strongSession = weakSession.promote();
162 EXPECT_EQ(nullptr, strongSession)
163 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
164 "Leaked sess: ")
165 << strongSession->getStrongCount() << " checked time " << i;
166
167 if (strongSession != nullptr) {
168 sleep(1);
169 }
170 }
Steven Moreland736664b2021-05-01 04:27:25 +0000171 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000172 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
Andrei Homescu96834632022-10-14 00:49:49 +0000174 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
175 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000176 }
Andrei Homescu96834632022-10-14 00:49:49 +0000177
178 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000179};
180
Yifan Hong1deca4b2021-09-10 16:16:44 -0700181static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700182 base::unique_fd serverFd(
183 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
184 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700185 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
186 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700187
188 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
189 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700190 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
191 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700192 }
193 return serverFd;
194}
195
David Brazdil21c887c2022-09-23 12:25:18 +0100196static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
197 base::unique_fd sockClient, sockServer;
198 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
199 int savedErrno = errno;
200 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
201 }
202
203 int zero = 0;
204 iovec iov{&zero, sizeof(zero)};
205 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
206 fds.emplace_back(std::move(sockServer));
207
208 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
209 int savedErrno = errno;
210 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
211 }
212 return std::move(sockClient);
213}
214
Andrei Homescu96834632022-10-14 00:49:49 +0000215std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
216 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
217 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
218 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
219 if (singleThreaded) {
220 ret += "_single_threaded";
221 }
222 if (noKernel) {
223 ret += "_no_kernel";
224 }
225 return ret;
226}
Andrei Homescu2a298012022-06-15 01:08:54 +0000227
Andrei Homescu96834632022-10-14 00:49:49 +0000228// This creates a new process serving an interface on a certain number of
229// threads.
230std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
231 const BinderRpcOptions& options) {
232 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000233
Andrei Homescu96834632022-10-14 00:49:49 +0000234 SocketType socketType = std::get<0>(GetParam());
235 RpcSecurity rpcSecurity = std::get<1>(GetParam());
236 uint32_t clientVersion = std::get<2>(GetParam());
237 uint32_t serverVersion = std::get<3>(GetParam());
238 bool singleThreaded = std::get<4>(GetParam());
239 bool noKernel = std::get<5>(GetParam());
240
241 std::string path = android::base::GetExecutableDirectory();
242 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
243 singleThreaded ? "_single_threaded" : "",
244 noKernel ? "_no_kernel" : "");
245
246 base::unique_fd bootstrapClientFd, bootstrapServerFd;
247 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
248 // This is because we cannot pass ParcelFileDescriptor over a pipe.
249 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &bootstrapServerFd)) {
250 int savedErrno = errno;
251 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
Andrei Homescua858b0e2022-08-01 23:43:09 +0000252 }
253
Andrei Homescu96834632022-10-14 00:49:49 +0000254 auto ret = std::make_unique<LinuxProcessSession>(
255 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
256 auto writeFd = std::to_string(writeEnd.get());
257 auto readFd = std::to_string(readEnd.get());
258 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
259 NULL);
260 }));
261
262 BinderRpcTestServerConfig serverConfig;
263 serverConfig.numThreads = options.numThreads;
264 serverConfig.socketType = static_cast<int32_t>(socketType);
265 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
266 serverConfig.serverVersion = serverVersion;
267 serverConfig.vsockPort = allocateVsockPort();
268 serverConfig.addr = allocateSocketAddress();
269 serverConfig.unixBootstrapFd = bootstrapServerFd.get();
270 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
271 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
272 static_cast<int32_t>(mode));
273 }
274 writeToFd(ret->host.writeEnd(), serverConfig);
275
276 std::vector<sp<RpcSession>> sessions;
277 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
278 for (size_t i = 0; i < options.numSessions; i++) {
279 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
David Brazdil21c887c2022-09-23 12:25:18 +0100280 }
281
Andrei Homescu96834632022-10-14 00:49:49 +0000282 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
283 BinderRpcTestClientInfo clientInfo;
284 for (const auto& session : sessions) {
285 auto& parcelableCert = clientInfo.certs.emplace_back();
286 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
287 }
288 writeToFd(ret->host.writeEnd(), clientInfo);
289
290 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
291 if (socketType == SocketType::INET) {
292 CHECK_NE(0, serverInfo.port);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000293 }
294
Andrei Homescu96834632022-10-14 00:49:49 +0000295 if (rpcSecurity == RpcSecurity::TLS) {
296 const auto& serverCert = serverInfo.cert.data;
297 CHECK_EQ(OK,
298 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700299 }
300
Andrei Homescu96834632022-10-14 00:49:49 +0000301 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000302
Andrei Homescu96834632022-10-14 00:49:49 +0000303 for (const auto& session : sessions) {
304 CHECK(session->setProtocolVersion(clientVersion));
305 session->setMaxIncomingThreads(options.numIncomingConnections);
306 session->setMaxOutgoingThreads(options.numOutgoingConnections);
307 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000308
Andrei Homescu96834632022-10-14 00:49:49 +0000309 switch (socketType) {
310 case SocketType::PRECONNECTED:
311 status = session->setupPreconnectedClient({}, [=]() {
312 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
313 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000314 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000315 case SocketType::UNIX:
316 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
317 break;
318 case SocketType::UNIX_BOOTSTRAP:
319 status = session->setupUnixDomainSocketBootstrapClient(
320 base::unique_fd(dup(bootstrapClientFd.get())));
321 break;
322 case SocketType::VSOCK:
323 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
324 break;
325 case SocketType::INET:
326 status = session->setupInetClient("127.0.0.1", serverInfo.port);
327 break;
328 default:
329 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000330 }
Andrei Homescu96834632022-10-14 00:49:49 +0000331 if (options.allowConnectFailure && status != OK) {
332 ret->sessions.clear();
333 break;
334 }
335 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
336 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000337 }
Andrei Homescu96834632022-10-14 00:49:49 +0000338 return ret;
339}
Steven Morelandc1635952021-04-01 16:20:47 +0000340
Andrei Homescua858b0e2022-08-01 23:43:09 +0000341TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
342 if (clientOrServerSingleThreaded()) {
343 GTEST_SKIP() << "This test requires multiple threads";
344 }
345
Steven Moreland5553ac42020-11-11 02:14:45 +0000346 constexpr size_t kNumThreads = 10;
347
Steven Moreland4313d7e2021-07-15 23:41:22 +0000348 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000349
350 EXPECT_OK(proc.rootIface->lock());
351
352 // block all but one thread taking locks
353 std::vector<std::thread> ts;
354 for (size_t i = 0; i < kNumThreads - 1; i++) {
355 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
356 }
357
Steven Morelanddd231e22022-09-08 19:47:49 +0000358 usleep(10000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000359
360 // other calls still work
361 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
362
Steven Morelanddd231e22022-09-08 19:47:49 +0000363 constexpr size_t blockTimeMs = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000364 size_t epochMsBefore = epochMillis();
365 // after this, we should never see a response within this time
366 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
367
368 // this call should be blocked for blockTimeMs
369 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
370
371 size_t epochMsAfter = epochMillis();
372 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
373
374 for (auto& t : ts) t.join();
375}
376
Andrei Homescu96834632022-10-14 00:49:49 +0000377static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
378 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 size_t epochMsBefore = epochMillis();
380
381 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700382 for (size_t i = 0; i < numCalls; i++) {
383 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000384 }
385
386 for (auto& t : ts) t.join();
387
388 size_t epochMsAfter = epochMillis();
389
Yifan Hong1f44f982021-10-08 17:16:47 -0700390 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000391
392 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700393 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
394}
395
Andrei Homescua858b0e2022-08-01 23:43:09 +0000396TEST_P(BinderRpc, ThreadPoolOverSaturated) {
397 if (clientOrServerSingleThreaded()) {
398 GTEST_SKIP() << "This test requires multiple threads";
399 }
400
Yifan Hong1f44f982021-10-08 17:16:47 -0700401 constexpr size_t kNumThreads = 10;
402 constexpr size_t kNumCalls = kNumThreads + 3;
403 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
404 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
405}
406
Andrei Homescua858b0e2022-08-01 23:43:09 +0000407TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
408 if (clientOrServerSingleThreaded()) {
409 GTEST_SKIP() << "This test requires multiple threads";
410 }
411
Yifan Hong1f44f982021-10-08 17:16:47 -0700412 constexpr size_t kNumThreads = 20;
413 constexpr size_t kNumOutgoingConnections = 10;
414 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
415 auto proc = createRpcTestSocketServerProcess(
416 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
417 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000418}
419
Andrei Homescua858b0e2022-08-01 23:43:09 +0000420TEST_P(BinderRpc, ThreadingStressTest) {
421 if (clientOrServerSingleThreaded()) {
422 GTEST_SKIP() << "This test requires multiple threads";
423 }
424
Steven Moreland5553ac42020-11-11 02:14:45 +0000425 constexpr size_t kNumClientThreads = 10;
426 constexpr size_t kNumServerThreads = 10;
427 constexpr size_t kNumCalls = 100;
428
Steven Moreland4313d7e2021-07-15 23:41:22 +0000429 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000430
431 std::vector<std::thread> threads;
432 for (size_t i = 0; i < kNumClientThreads; i++) {
433 threads.push_back(std::thread([&] {
434 for (size_t j = 0; j < kNumCalls; j++) {
435 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000436 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000437 EXPECT_EQ(proc.rootBinder, out);
438 }
439 }));
440 }
441
442 for (auto& t : threads) t.join();
443}
444
Steven Moreland925ba0a2021-09-17 18:06:32 -0700445static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
446 std::vector<std::thread> threads;
447 for (size_t i = 0; i < threadCount; i++) {
448 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
449 }
450 for (auto& t : threads) t.join();
451}
452
Andrei Homescua858b0e2022-08-01 23:43:09 +0000453TEST_P(BinderRpc, OnewayStressTest) {
454 if (clientOrServerSingleThreaded()) {
455 GTEST_SKIP() << "This test requires multiple threads";
456 }
457
Steven Morelandc6046982021-04-20 00:49:42 +0000458 constexpr size_t kNumClientThreads = 10;
459 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700460 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000461
Steven Moreland4313d7e2021-07-15 23:41:22 +0000462 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000463
464 std::vector<std::thread> threads;
465 for (size_t i = 0; i < kNumClientThreads; i++) {
466 threads.push_back(std::thread([&] {
467 for (size_t j = 0; j < kNumCalls; j++) {
468 EXPECT_OK(proc.rootIface->sendString("a"));
469 }
Steven Morelandc6046982021-04-20 00:49:42 +0000470 }));
471 }
472
473 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700474
475 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000476}
477
Frederick Mayleb0221d12022-10-03 23:10:53 +0000478TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
479 if (!supportsFdTransport()) {
480 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
481 }
482 if (clientOrServerSingleThreaded()) {
483 GTEST_SKIP() << "This test requires multiple threads";
484 }
485
486 // This test forces a oneway transaction to be queued by issuing two
487 // `blockingSendFdOneway` calls, then drains the queue by issuing two
488 // `blockingRecvFd` calls.
489 //
490 // For more details about the queuing semantics see
491 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
492
493 auto proc = createRpcTestSocketServerProcess({
494 .numThreads = 3,
495 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
496 .serverSupportedFileDescriptorTransportModes =
497 {RpcSession::FileDescriptorTransportMode::UNIX},
498 });
499
500 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
501 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
502 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
503 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
504
505 android::os::ParcelFileDescriptor fdA;
506 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
507 std::string result;
508 CHECK(android::base::ReadFdToString(fdA.get(), &result));
509 EXPECT_EQ(result, "a");
510
511 android::os::ParcelFileDescriptor fdB;
512 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
513 CHECK(android::base::ReadFdToString(fdB.get(), &result));
514 EXPECT_EQ(result, "b");
515}
516
Andrei Homescua858b0e2022-08-01 23:43:09 +0000517TEST_P(BinderRpc, OnewayCallQueueing) {
518 if (clientOrServerSingleThreaded()) {
519 GTEST_SKIP() << "This test requires multiple threads";
520 }
521
Steven Moreland5553ac42020-11-11 02:14:45 +0000522 constexpr size_t kNumSleeps = 10;
523 constexpr size_t kNumExtraServerThreads = 4;
524 constexpr size_t kSleepMs = 50;
525
526 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000527 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000528
529 EXPECT_OK(proc.rootIface->lock());
530
Steven Moreland1c678802021-09-17 16:48:47 -0700531 size_t epochMsBefore = epochMillis();
532
533 // all these *Async commands should be queued on the server sequentially,
534 // even though there are multiple threads.
535 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000536 proc.rootIface->sleepMsAsync(kSleepMs);
537 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000538 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
539
Steven Moreland1c678802021-09-17 16:48:47 -0700540 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700542
Steven Moreland5553ac42020-11-11 02:14:45 +0000543 size_t epochMsAfter = epochMillis();
544
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000545 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000546
Steven Moreland925ba0a2021-09-17 18:06:32 -0700547 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000548}
549
Andrei Homescua858b0e2022-08-01 23:43:09 +0000550TEST_P(BinderRpc, OnewayCallExhaustion) {
551 if (clientOrServerSingleThreaded()) {
552 GTEST_SKIP() << "This test requires multiple threads";
553 }
554
Steven Morelandd45be622021-06-04 02:19:37 +0000555 constexpr size_t kNumClients = 2;
556 constexpr size_t kTooLongMs = 1000;
557
Steven Moreland4313d7e2021-07-15 23:41:22 +0000558 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000559
560 // Build up oneway calls on the second session to make sure it terminates
561 // and shuts down. The first session should be unaffected (proc destructor
562 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000563 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000564
565 std::vector<std::thread> threads;
566 for (size_t i = 0; i < kNumClients; i++) {
567 // one of these threads will get stuck queueing a transaction once the
568 // socket fills up, the other will be able to fill up transactions on
569 // this object
570 threads.push_back(std::thread([&] {
571 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
572 }
573 }));
574 }
575 for (auto& t : threads) t.join();
576
577 Status status = iface->sleepMsAsync(kTooLongMs);
578 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
579
Steven Moreland798e0d12021-07-14 23:19:25 +0000580 // now that it has died, wait for the remote session to shutdown
581 std::vector<int32_t> remoteCounts;
582 do {
583 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
584 } while (remoteCounts.size() == kNumClients);
585
Steven Morelandd45be622021-06-04 02:19:37 +0000586 // the second session should be shutdown in the other process by the time we
587 // are able to join above (it'll only be hung up once it finishes processing
588 // any pending commands). We need to erase this session from the record
589 // here, so that the destructor for our session won't check that this
590 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000591 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000592}
593
Devin Moore66d5b7a2022-07-07 21:42:10 +0000594TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000595 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000596 GTEST_SKIP() << "This test requires multiple threads";
597 }
598 class MyDeathRec : public IBinder::DeathRecipient {
599 public:
600 void binderDied(const wp<IBinder>& /* who */) override {
601 dead = true;
602 mCv.notify_one();
603 }
604 std::mutex mMtx;
605 std::condition_variable mCv;
606 bool dead = false;
607 };
608
609 // Death recipient needs to have an incoming connection to be called
610 auto proc = createRpcTestSocketServerProcess(
611 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
612
613 auto dr = sp<MyDeathRec>::make();
614 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
615
616 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
617 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
618 }
619
620 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000621 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000622
623 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000624 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000625 proc.expectAlreadyShutdown = true;
626}
627
628TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000629 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000630 GTEST_SKIP() << "This test requires multiple threads";
631 }
632 class MyDeathRec : public IBinder::DeathRecipient {
633 public:
634 void binderDied(const wp<IBinder>& /* who */) override {
635 dead = true;
636 mCv.notify_one();
637 }
638 std::mutex mMtx;
639 std::condition_variable mCv;
640 bool dead = false;
641 };
642
643 // Death recipient needs to have an incoming connection to be called
644 auto proc = createRpcTestSocketServerProcess(
645 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
646
647 auto dr = sp<MyDeathRec>::make();
648 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
649
650 // Explicitly calling shutDownAndWait will cause the death recipients
651 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000652 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000653
654 std::unique_lock<std::mutex> lock(dr->mMtx);
655 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000656 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000657 }
658 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
659
Andrei Homescu96834632022-10-14 00:49:49 +0000660 proc.proc->terminate();
661 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000662 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
663 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
664 });
665 proc.expectAlreadyShutdown = true;
666}
667
668TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
669 class MyDeathRec : public IBinder::DeathRecipient {
670 public:
671 void binderDied(const wp<IBinder>& /* who */) override {}
672 };
673
674 auto proc = createRpcTestSocketServerProcess(
675 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
676
677 auto dr = sp<MyDeathRec>::make();
678 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
679 "Cannot register a DeathRecipient without any incoming connections.");
680}
681
682TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000683 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000684 GTEST_SKIP() << "This test requires multiple threads";
685 }
686 class MyDeathRec : public IBinder::DeathRecipient {
687 public:
688 void binderDied(const wp<IBinder>& /* who */) override {
689 GTEST_FAIL() << "This should not be called after unlinkToDeath";
690 }
691 };
692
693 // Death recipient needs to have an incoming connection to be called
694 auto proc = createRpcTestSocketServerProcess(
695 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
696
697 auto dr = sp<MyDeathRec>::make();
698 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
699 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
700
701 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
702 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
703 }
704
705 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000706 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000707 proc.expectAlreadyShutdown = true;
708}
709
Steven Morelandc1635952021-04-01 16:20:47 +0000710TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000711 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000712 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000713
714 // make sure there is some state during crash
715 // 1. we hold their binder
716 sp<IBinderRpcSession> session;
717 EXPECT_OK(proc.rootIface->openSession("happy", &session));
718 // 2. they hold our binder
719 sp<IBinder> binder = new BBinder();
720 EXPECT_OK(proc.rootIface->holdBinder(binder));
721
722 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
723 << "Do death cleanup: " << doDeathCleanup;
724
Andrei Homescu96834632022-10-14 00:49:49 +0000725 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000726 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
727 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
728 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000729 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000730 }
731}
732
Steven Morelandd7302072021-05-15 01:32:04 +0000733TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000734 // This test only works if the current process shared the internal state of
735 // ProcessState with the service across the call to fork(). Both the static
736 // libraries and libbinder.so have their own separate copies of all the
737 // globals, so the test only works when the test client and service both use
738 // libbinder.so (when using static libraries, even a client and service
739 // using the same kind of static library should have separate copies of the
740 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000741 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000742 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
743 "at build time.";
744 }
745
Steven Moreland4313d7e2021-07-15 23:41:22 +0000746 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000747
Andrei Homescu2a298012022-06-15 01:08:54 +0000748 // we can't allocate IPCThreadState so actually the first time should
749 // succeed :(
750 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000751
752 // second time! we catch the error :)
753 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
754
Andrei Homescu96834632022-10-14 00:49:49 +0000755 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000756 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
757 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
758 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000759 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000760}
761
Frederick Mayle69a0c992022-05-26 20:38:39 +0000762TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
763 auto proc = createRpcTestSocketServerProcess({
764 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
765 .serverSupportedFileDescriptorTransportModes =
766 {RpcSession::FileDescriptorTransportMode::UNIX},
767 .allowConnectFailure = true,
768 });
Andrei Homescu96834632022-10-14 00:49:49 +0000769 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
770 proc.proc->terminate();
771 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000772 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
773 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
774 });
775 proc.expectAlreadyShutdown = true;
776}
777
778TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
779 auto proc = createRpcTestSocketServerProcess({
780 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
781 .serverSupportedFileDescriptorTransportModes =
782 {RpcSession::FileDescriptorTransportMode::NONE},
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, FileDescriptorTransportOptionalUnix) {
795 auto proc = createRpcTestSocketServerProcess({
796 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
797 .serverSupportedFileDescriptorTransportModes =
798 {RpcSession::FileDescriptorTransportMode::NONE,
799 RpcSession::FileDescriptorTransportMode::UNIX},
800 });
801
802 android::os::ParcelFileDescriptor out;
803 auto status = proc.rootIface->echoAsFile("hello", &out);
804 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
805}
806
807TEST_P(BinderRpc, ReceiveFile) {
808 auto proc = createRpcTestSocketServerProcess({
809 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
810 .serverSupportedFileDescriptorTransportModes =
811 {RpcSession::FileDescriptorTransportMode::UNIX},
812 });
813
814 android::os::ParcelFileDescriptor out;
815 auto status = proc.rootIface->echoAsFile("hello", &out);
816 if (!supportsFdTransport()) {
817 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
818 return;
819 }
820 ASSERT_TRUE(status.isOk()) << status;
821
822 std::string result;
823 CHECK(android::base::ReadFdToString(out.get(), &result));
824 EXPECT_EQ(result, "hello");
825}
826
827TEST_P(BinderRpc, SendFiles) {
828 auto proc = createRpcTestSocketServerProcess({
829 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
830 .serverSupportedFileDescriptorTransportModes =
831 {RpcSession::FileDescriptorTransportMode::UNIX},
832 });
833
834 std::vector<android::os::ParcelFileDescriptor> files;
835 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
836 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
837 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
838 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
839
840 android::os::ParcelFileDescriptor out;
841 auto status = proc.rootIface->concatFiles(files, &out);
842 if (!supportsFdTransport()) {
843 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
844 return;
845 }
846 ASSERT_TRUE(status.isOk()) << status;
847
848 std::string result;
849 CHECK(android::base::ReadFdToString(out.get(), &result));
850 EXPECT_EQ(result, "123abcd");
851}
852
853TEST_P(BinderRpc, SendMaxFiles) {
854 if (!supportsFdTransport()) {
855 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
856 }
857
858 auto proc = createRpcTestSocketServerProcess({
859 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
860 .serverSupportedFileDescriptorTransportModes =
861 {RpcSession::FileDescriptorTransportMode::UNIX},
862 });
863
864 std::vector<android::os::ParcelFileDescriptor> files;
865 for (int i = 0; i < 253; i++) {
866 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
867 }
868
869 android::os::ParcelFileDescriptor out;
870 auto status = proc.rootIface->concatFiles(files, &out);
871 ASSERT_TRUE(status.isOk()) << status;
872
873 std::string result;
874 CHECK(android::base::ReadFdToString(out.get(), &result));
875 EXPECT_EQ(result, std::string(253, 'a'));
876}
877
878TEST_P(BinderRpc, SendTooManyFiles) {
879 if (!supportsFdTransport()) {
880 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
881 }
882
883 auto proc = createRpcTestSocketServerProcess({
884 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
885 .serverSupportedFileDescriptorTransportModes =
886 {RpcSession::FileDescriptorTransportMode::UNIX},
887 });
888
889 std::vector<android::os::ParcelFileDescriptor> files;
890 for (int i = 0; i < 254; i++) {
891 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
892 }
893
894 android::os::ParcelFileDescriptor out;
895 auto status = proc.rootIface->concatFiles(files, &out);
896 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
897}
898
Steven Moreland37aff182021-03-26 02:04:16 +0000899TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000900 if constexpr (!kEnableSharedLibs) {
901 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
902 }
903
Steven Moreland4313d7e2021-07-15 23:41:22 +0000904 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000905
906 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
907 ASSERT_NE(binder, nullptr);
908
909 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
910}
911
912TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000913 if constexpr (!kEnableSharedLibs) {
914 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
915 }
916
Steven Moreland4313d7e2021-07-15 23:41:22 +0000917 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000918
919 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
920 ASSERT_NE(binder, nullptr);
921
922 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
923 ASSERT_NE(ndkBinder, nullptr);
924
925 std::string out;
926 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
927 ASSERT_TRUE(status.isOk()) << status.getDescription();
928 ASSERT_EQ("aoeuaoeu", out);
929}
930
Steven Moreland5553ac42020-11-11 02:14:45 +0000931ssize_t countFds() {
932 DIR* dir = opendir("/proc/self/fd/");
933 if (dir == nullptr) return -1;
934 ssize_t ret = 0;
935 dirent* ent;
936 while ((ent = readdir(dir)) != nullptr) ret++;
937 closedir(dir);
938 return ret;
939}
940
Andrei Homescua858b0e2022-08-01 23:43:09 +0000941TEST_P(BinderRpc, Fds) {
942 if (serverSingleThreaded()) {
943 GTEST_SKIP() << "This test requires multiple threads";
944 }
945
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 ssize_t beforeFds = countFds();
947 ASSERT_GE(beforeFds, 0);
948 {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000949 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
951 }
952 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
953}
954
Steven Morelandda573042021-06-12 01:13:45 +0000955static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -0700956 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +0000957 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +0000958
Andrei Homescu992a4052022-06-28 21:26:18 +0000959 android::base::unique_fd serverFd(
960 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
961 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
962
963 sockaddr_vm serverAddr{
964 .svm_family = AF_VSOCK,
965 .svm_port = vsockPort,
966 .svm_cid = VMADDR_CID_ANY,
967 };
968 int ret = TEMP_FAILURE_RETRY(
969 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
970 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
971 strerror(errno));
972
973 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
974 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
975 strerror(errno));
976
977 // Try to connect to the server using the VMADDR_CID_LOCAL cid
978 // to see if the kernel supports it. It's safe to use a blocking
979 // connect because vsock sockets have a 2 second connection timeout,
980 // and they return ETIMEDOUT after that.
981 android::base::unique_fd connectFd(
982 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
983 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
984 strerror(errno));
985
986 bool success = false;
987 sockaddr_vm connectAddr{
988 .svm_family = AF_VSOCK,
989 .svm_port = vsockPort,
990 .svm_cid = VMADDR_CID_LOCAL,
991 };
992 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
993 sizeof(connectAddr)));
994 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
995 android::base::unique_fd acceptFd;
996 while (true) {
997 pollfd pfd[]{
998 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
999 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1000 };
1001 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1002 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1003
1004 if (pfd[0].revents & POLLIN) {
1005 sockaddr_vm acceptAddr;
1006 socklen_t acceptAddrLen = sizeof(acceptAddr);
1007 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1008 reinterpret_cast<sockaddr*>(&acceptAddr),
1009 &acceptAddrLen, SOCK_CLOEXEC));
1010 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1011 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1012 "Truncated address");
1013
1014 // Store the fd in acceptFd so we keep the connection alive
1015 // while polling connectFd
1016 acceptFd.reset(ret);
1017 }
1018
1019 if (pfd[1].revents & POLLOUT) {
1020 // Connect either succeeded or timed out
1021 int connectErrno;
1022 socklen_t connectErrnoLen = sizeof(connectErrno);
1023 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1024 &connectErrnoLen);
1025 LOG_ALWAYS_FATAL_IF(ret == -1,
1026 "Could not getsockopt() after connect() "
1027 "on non-blocking socket: %s.",
1028 strerror(errno));
1029
1030 // We're done, this is all we wanted
1031 success = connectErrno == 0;
1032 break;
1033 }
1034 }
1035 } else {
1036 success = ret == 0;
1037 }
1038
1039 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1040
1041 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001042}
1043
Yifan Hong1deca4b2021-09-10 16:16:44 -07001044static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
David Brazdil21c887c2022-09-23 12:25:18 +01001045 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001046
1047 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001048
1049 static bool hasVsockLoopback = testSupportVsockLoopback();
1050
1051 if (hasVsockLoopback) {
1052 ret.push_back(SocketType::VSOCK);
1053 }
1054
1055 return ret;
1056}
1057
Frederick Mayledc07cf82022-05-26 20:30:12 +00001058static std::vector<uint32_t> testVersions() {
1059 std::vector<uint32_t> versions;
1060 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1061 versions.push_back(i);
1062 }
1063 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1064 return versions;
1065}
1066
Yifan Hong702115c2021-06-24 15:39:18 -07001067INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1068 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001069 ::testing::ValuesIn(RpcSecurityValues()),
1070 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001071 ::testing::ValuesIn(testVersions()),
1072 ::testing::Values(false, true),
1073 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001074 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001075
Yifan Hong702115c2021-06-24 15:39:18 -07001076class BinderRpcServerRootObject
1077 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001078
1079TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1080 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1081 auto setRootObject = [](bool isStrong) -> SetFn {
1082 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1083 };
1084
Yifan Hong702115c2021-06-24 15:39:18 -07001085 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1086 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001087 auto binder1 = sp<BBinder>::make();
1088 IBinder* binderRaw1 = binder1.get();
1089 setRootObject(isStrong1)(server.get(), binder1);
1090 EXPECT_EQ(binderRaw1, server->getRootObject());
1091 binder1.clear();
1092 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1093
1094 auto binder2 = sp<BBinder>::make();
1095 IBinder* binderRaw2 = binder2.get();
1096 setRootObject(isStrong2)(server.get(), binder2);
1097 EXPECT_EQ(binderRaw2, server->getRootObject());
1098 binder2.clear();
1099 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1100}
1101
1102INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001103 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1104 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001105
Yifan Hong1a235852021-05-13 16:07:47 -07001106class OneOffSignal {
1107public:
1108 // If notify() was previously called, or is called within |duration|, return true; else false.
1109 template <typename R, typename P>
1110 bool wait(std::chrono::duration<R, P> duration) {
1111 std::unique_lock<std::mutex> lock(mMutex);
1112 return mCv.wait_for(lock, duration, [this] { return mValue; });
1113 }
1114 void notify() {
1115 std::unique_lock<std::mutex> lock(mMutex);
1116 mValue = true;
1117 lock.unlock();
1118 mCv.notify_all();
1119 }
1120
1121private:
1122 std::mutex mMutex;
1123 std::condition_variable mCv;
1124 bool mValue = false;
1125};
1126
Yifan Hong194acf22021-06-29 18:44:56 -07001127TEST(BinderRpc, Java) {
1128#if !defined(__ANDROID__)
1129 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1130 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1131 "to binderHostDeviceTest. Hence, just disable this test on host.";
1132#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001133 if constexpr (!kEnableKernelIpc) {
1134 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1135 "at build time.";
1136 }
1137
Yifan Hong194acf22021-06-29 18:44:56 -07001138 sp<IServiceManager> sm = defaultServiceManager();
1139 ASSERT_NE(nullptr, sm);
1140 // Any Java service with non-empty getInterfaceDescriptor() would do.
1141 // Let's pick batteryproperties.
1142 auto binder = sm->checkService(String16("batteryproperties"));
1143 ASSERT_NE(nullptr, binder);
1144 auto descriptor = binder->getInterfaceDescriptor();
1145 ASSERT_GE(descriptor.size(), 0);
1146 ASSERT_EQ(OK, binder->pingBinder());
1147
1148 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001149 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001150 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001151 auto socket = rpcServer->releaseServer();
1152
1153 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001154 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1155
Yifan Honge3caaf22022-01-12 14:46:56 -08001156 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1157 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001158 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001159 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1160 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001161 << statusToString(setRpcClientDebugStatus);
1162 GTEST_SKIP();
1163 }
1164
1165 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001166
1167 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001168 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001169 auto rpcBinder = rpcSession->getRootObject();
1170 ASSERT_NE(nullptr, rpcBinder);
1171
1172 ASSERT_EQ(OK, rpcBinder->pingBinder());
1173
1174 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1175 << "getInterfaceDescriptor should not crash system_server";
1176 ASSERT_EQ(OK, rpcBinder->pingBinder());
1177}
1178
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001179class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1180public:
1181 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1182 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1183 std::to_string(std::get<1>(info.param));
1184 }
1185};
1186
1187TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1188 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1189 int sinkFd = sink.get();
1190 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1191 server->setProtocolVersion(std::get<1>(GetParam()));
1192 ASSERT_FALSE(server->hasServer());
1193 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1194 ASSERT_TRUE(server->hasServer());
1195 base::unique_fd retrieved = server->releaseServer();
1196 ASSERT_FALSE(server->hasServer());
1197 ASSERT_EQ(sinkFd, retrieved.get());
1198}
1199
1200TEST_P(BinderRpcServerOnly, Shutdown) {
1201 if constexpr (!kEnableRpcThreads) {
1202 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1203 }
1204
1205 auto addr = allocateSocketAddress();
1206 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1207 server->setProtocolVersion(std::get<1>(GetParam()));
1208 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1209 auto joinEnds = std::make_shared<OneOffSignal>();
1210
1211 // If things are broken and the thread never stops, don't block other tests. Because the thread
1212 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1213 // shared pointers are passed.
1214 std::thread([server, joinEnds] {
1215 server->join();
1216 joinEnds->notify();
1217 }).detach();
1218
1219 bool shutdown = false;
1220 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001221 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001222 if (server->shutdown()) shutdown = true;
1223 }
1224 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1225
1226 ASSERT_TRUE(joinEnds->wait(2s))
1227 << "After server->shutdown() returns true, join() did not stop after 2s";
1228}
1229
Frederick Mayledc07cf82022-05-26 20:30:12 +00001230INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1231 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1232 ::testing::ValuesIn(testVersions())),
1233 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001234
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001235class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001236public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001237 // Only parameterized only server version because `RpcSession` is bypassed
1238 // in the client half of the tests.
1239 using Param =
1240 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001241 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001242
1243 // A server that handles client socket connections.
1244 class Server {
1245 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001246 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1247
Yifan Hong1deca4b2021-09-10 16:16:44 -07001248 explicit Server() {}
1249 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001250 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001251 [[nodiscard]] AssertionResult setUp(
1252 const Param& param,
1253 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001254 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001255 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001256 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001257 switch (socketType) {
1258 case SocketType::PRECONNECTED: {
1259 return AssertionFailure() << "Not supported by this test";
1260 } break;
1261 case SocketType::UNIX: {
1262 auto addr = allocateSocketAddress();
1263 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1264 if (status != OK) {
1265 return AssertionFailure()
1266 << "setupUnixDomainServer: " << statusToString(status);
1267 }
1268 mConnectToServer = [addr] {
1269 return connectTo(UnixSocketAddress(addr.c_str()));
1270 };
1271 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001272 case SocketType::UNIX_BOOTSTRAP: {
1273 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1274 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1275 return AssertionFailure() << "Socketpair() failed";
1276 }
1277 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1278 std::move(bootstrapFdServer));
1279 if (status != OK) {
1280 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1281 << statusToString(status);
1282 }
1283 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1284 mAcceptConnection = &Server::recvmsgServerConnection;
1285 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1286 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001287 case SocketType::VSOCK: {
1288 auto port = allocateVsockPort();
1289 auto status = rpcServer->setupVsockServer(port);
1290 if (status != OK) {
1291 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1292 }
1293 mConnectToServer = [port] {
1294 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1295 };
1296 } break;
1297 case SocketType::INET: {
1298 unsigned int port;
1299 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1300 if (status != OK) {
1301 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1302 }
1303 mConnectToServer = [port] {
1304 const char* addr = kLocalInetAddress;
1305 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1306 if (aiStart == nullptr) return base::unique_fd{};
1307 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1308 auto fd = connectTo(
1309 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1310 if (fd.ok()) return fd;
1311 }
1312 ALOGE("None of the socket address resolved for %s:%u can be connected",
1313 addr, port);
1314 return base::unique_fd{};
1315 };
1316 }
1317 }
1318 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001319 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001320 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001321 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1322 mSetup = true;
1323 return AssertionSuccess();
1324 }
1325 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1326 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1327 return mCertVerifier;
1328 }
1329 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1330 void start() {
1331 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1332 mThread = std::make_unique<std::thread>(&Server::run, this);
1333 }
David Brazdil21c887c2022-09-23 12:25:18 +01001334
1335 base::unique_fd acceptServerConnection() {
1336 return base::unique_fd(TEMP_FAILURE_RETRY(
1337 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1338 }
1339
1340 base::unique_fd recvmsgServerConnection() {
1341 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1342 int buf;
1343 iovec iov{&buf, sizeof(buf)};
1344
1345 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1346 int savedErrno = errno;
1347 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1348 }
1349 if (fds.size() != 1) {
1350 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1351 }
1352 return std::move(std::get<base::unique_fd>(fds[0]));
1353 }
1354
Yifan Hong1deca4b2021-09-10 16:16:44 -07001355 void run() {
1356 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1357
1358 std::vector<std::thread> threads;
1359 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001360 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001361 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1362 }
1363
1364 for (auto& thread : threads) thread.join();
1365 }
1366 void handleOne(android::base::unique_fd acceptedFd) {
1367 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001368 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001369 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001370 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001371 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001372 }
Yifan Honge07d2732021-09-13 21:59:14 -07001373 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001374 shutdown();
1375 join();
1376 }
1377 void shutdown() { mFdTrigger->trigger(); }
1378
1379 void setPostConnect(
1380 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1381 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001382 }
1383
1384 private:
1385 std::unique_ptr<std::thread> mThread;
1386 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001387 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001388 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001389 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001390 std::unique_ptr<RpcTransportCtx> mCtx;
1391 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1392 std::make_shared<RpcCertificateVerifierSimple>();
1393 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001394 // The function invoked after connection and handshake. By default, it is
1395 // |defaultPostConnect| that sends |kMessage| to the client.
1396 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1397 Server::defaultPostConnect;
1398
1399 void join() {
1400 if (mThread != nullptr) {
1401 mThread->join();
1402 mThread = nullptr;
1403 }
1404 }
1405
1406 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1407 FdTrigger* fdTrigger) {
1408 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001409 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001410 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001411 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001412 if (status != OK) return AssertionFailure() << statusToString(status);
1413 return AssertionSuccess();
1414 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001415 };
1416
1417 class Client {
1418 public:
1419 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1420 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001421 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001422 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1423 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001424 mFdTrigger = FdTrigger::make();
1425 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1426 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1427 return AssertionSuccess();
1428 }
1429 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1430 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1431 return mCertVerifier;
1432 }
Yifan Hong67519322021-09-13 18:51:16 -07001433 // connect() and do handshake
1434 bool setUpTransport() {
1435 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001436 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001437 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1438 return mClientTransport != nullptr;
1439 }
1440 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1441 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1442 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001443 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001444 status_t readStatus =
1445 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001446 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001447 if (readStatus != OK) {
1448 return AssertionFailure() << statusToString(readStatus);
1449 }
1450 if (readMessage != expectedMessage) {
1451 return AssertionFailure()
1452 << "Expected " << expectedMessage << ", actual " << readMessage;
1453 }
1454 return AssertionSuccess();
1455 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001456 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001457 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001458 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1459 return;
1460 }
1461 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001462 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001463 }
1464
Pawan49d74cb2022-08-03 21:19:11 +00001465 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1466
Yifan Hong1deca4b2021-09-10 16:16:44 -07001467 private:
1468 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001469 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001470 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1471 std::unique_ptr<RpcTransportCtx> mCtx;
1472 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1473 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001474 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001475 };
1476
1477 // Make A trust B.
1478 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001479 static status_t trust(RpcSecurity rpcSecurity,
1480 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1481 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001482 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001483 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1484 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1485 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001486 }
1487
1488 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001489};
1490
1491class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1492public:
1493 using Server = RpcTransportTestUtils::Server;
1494 using Client = RpcTransportTestUtils::Client;
1495 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001496 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001497 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1498 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001499 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001500 return ret;
1501 }
1502 static std::vector<ParamType> getRpcTranportTestParams() {
1503 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001504 for (auto serverVersion : testVersions()) {
1505 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1506 for (auto rpcSecurity : RpcSecurityValues()) {
1507 switch (rpcSecurity) {
1508 case RpcSecurity::RAW: {
1509 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1510 } break;
1511 case RpcSecurity::TLS: {
1512 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1513 serverVersion);
1514 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1515 serverVersion);
1516 } break;
1517 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001518 }
1519 }
1520 }
1521 return ret;
1522 }
1523 template <typename A, typename B>
1524 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001525 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1526 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001527 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1528 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001529 void SetUp() override {
1530 if constexpr (!kEnableRpcThreads) {
1531 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1532 }
1533 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001534};
1535
1536TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001537 auto server = std::make_unique<Server>();
1538 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539
1540 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001541 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001542
1543 ASSERT_EQ(OK, trust(&client, server));
1544 ASSERT_EQ(OK, trust(server, &client));
1545
1546 server->start();
1547 client.run();
1548}
1549
1550TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001551 auto server = std::make_unique<Server>();
1552 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001553
1554 std::vector<Client> clients;
1555 for (int i = 0; i < 2; i++) {
1556 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001557 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001558 ASSERT_EQ(OK, trust(&client, server));
1559 ASSERT_EQ(OK, trust(server, &client));
1560 }
1561
1562 server->start();
1563 for (auto& client : clients) client.run();
1564}
1565
1566TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001567 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1568 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001569
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001570 auto untrustedServer = std::make_unique<Server>();
1571 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001572
1573 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001574 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001575
1576 ASSERT_EQ(OK, trust(untrustedServer, &client));
1577
1578 untrustedServer->start();
1579
1580 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1581 // the client can't verify the server's identity.
1582 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1583 client.run(handshakeOk);
1584}
1585TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001586 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1587 (void)serverVersion;
1588
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001589 auto validServer = std::make_unique<Server>();
1590 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001591
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001592 auto maliciousServer = std::make_unique<Server>();
1593 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001594
1595 Client client(maliciousServer->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, validServer));
1599 ASSERT_EQ(OK, trust(validServer, &client));
1600 ASSERT_EQ(OK, trust(maliciousServer, &client));
1601
1602 maliciousServer->start();
1603
1604 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1605 // the client can't verify the server's identity.
1606 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1607 client.run(handshakeOk);
1608}
1609
1610TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001611 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1612 (void)serverVersion;
1613
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001614 auto server = std::make_unique<Server>();
1615 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001616
1617 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001618 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619
1620 ASSERT_EQ(OK, trust(&client, server));
1621
1622 server->start();
1623
1624 // For TLS, Client should be able to verify server's identity, so client should see
1625 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1626 // identity and should drop the connection, so client shouldn't be able to read anything.
1627 bool readOk = rpcSecurity != RpcSecurity::TLS;
1628 client.run(true, readOk);
1629}
1630
1631TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001632 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1633 (void)serverVersion;
1634
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001635 auto server = std::make_unique<Server>();
1636 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637
1638 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001639 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001641 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642
1643 ASSERT_EQ(OK, trust(&validClient, server));
1644 ASSERT_EQ(OK, trust(&maliciousClient, server));
1645
1646 server->start();
1647
1648 // See UntrustedClient.
1649 bool readOk = rpcSecurity != RpcSecurity::TLS;
1650 maliciousClient.run(true, readOk);
1651}
1652
Yifan Hong67519322021-09-13 18:51:16 -07001653TEST_P(RpcTransportTest, Trigger) {
1654 std::string msg2 = ", world!";
1655 std::mutex writeMutex;
1656 std::condition_variable writeCv;
1657 bool shouldContinueWriting = false;
1658 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001659 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001660 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001661 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1662 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001663 if (status != OK) return AssertionFailure() << statusToString(status);
1664
1665 {
1666 std::unique_lock<std::mutex> lock(writeMutex);
1667 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1668 return AssertionFailure() << "write barrier not cleared in time!";
1669 }
1670 }
1671
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001672 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001673 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1674 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001675 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001676 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001677 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001678 << statusToString(status);
1679 return AssertionSuccess();
1680 };
1681
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001682 auto server = std::make_unique<Server>();
1683 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001684
1685 // Set up client
1686 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001687 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001688
1689 // Exchange keys
1690 ASSERT_EQ(OK, trust(&client, server));
1691 ASSERT_EQ(OK, trust(server, &client));
1692
1693 server->setPostConnect(serverPostConnect);
1694
Yifan Hong67519322021-09-13 18:51:16 -07001695 server->start();
1696 // connect() to server and do handshake
1697 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001698 // read the first message. This ensures that server has finished handshake and start handling
1699 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001700 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001701 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1702 // write is on an FdTrigger that has been shut down.
1703 server->shutdown();
1704 // Continues server thread to write the second message.
1705 {
Yifan Hong22211f82021-09-14 12:32:25 -07001706 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001707 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001708 }
Yifan Hong22211f82021-09-14 12:32:25 -07001709 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001710 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001711 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001712 // On the client side, second read fails with DEAD_OBJECT
1713 ASSERT_FALSE(client.readMessage(msg2));
1714}
1715
Pawan49d74cb2022-08-03 21:19:11 +00001716TEST_P(RpcTransportTest, CheckWaitingForRead) {
1717 std::mutex readMutex;
1718 std::condition_variable readCv;
1719 bool shouldContinueReading = false;
1720 // Server will write data on transport once its started
1721 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1722 std::string message(RpcTransportTestUtils::kMessage);
1723 iovec messageIov{message.data(), message.size()};
1724 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1725 std::nullopt, nullptr);
1726 if (status != OK) return AssertionFailure() << statusToString(status);
1727
1728 {
1729 std::unique_lock<std::mutex> lock(readMutex);
1730 shouldContinueReading = true;
1731 lock.unlock();
1732 readCv.notify_all();
1733 }
1734 return AssertionSuccess();
1735 };
1736
1737 // Setup Server and client
1738 auto server = std::make_unique<Server>();
1739 ASSERT_TRUE(server->setUp(GetParam()));
1740
1741 Client client(server->getConnectToServerFn());
1742 ASSERT_TRUE(client.setUp(GetParam()));
1743
1744 ASSERT_EQ(OK, trust(&client, server));
1745 ASSERT_EQ(OK, trust(server, &client));
1746 server->setPostConnect(serverPostConnect);
1747
1748 server->start();
1749 ASSERT_TRUE(client.setUpTransport());
1750 {
1751 // Wait till server writes data
1752 std::unique_lock<std::mutex> lock(readMutex);
1753 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1754 }
1755
1756 // Since there is no read polling here, we will get polling count 0
1757 ASSERT_FALSE(client.isTransportWaiting());
1758 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1759 // Thread should increment polling count, read and decrement polling count
1760 // Again, polling count should be zero here
1761 ASSERT_FALSE(client.isTransportWaiting());
1762
1763 server->shutdown();
1764}
1765
Yifan Hong1deca4b2021-09-10 16:16:44 -07001766INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001767 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001768 RpcTransportTest::PrintParamInfo);
1769
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001770class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001771 : public testing::TestWithParam<
1772 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001773public:
1774 template <typename A, typename B>
1775 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001776 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1777 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001778 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1779 }
1780 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001781 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1782 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1783 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001784 };
1785};
1786
1787TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001788 if constexpr (!kEnableRpcThreads) {
1789 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1790 }
1791
Frederick Mayledc07cf82022-05-26 20:30:12 +00001792 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001793
1794 std::vector<uint8_t> pkeyData, certData;
1795 {
1796 auto pkey = makeKeyPairForSelfSignedCert();
1797 ASSERT_NE(nullptr, pkey);
1798 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1799 ASSERT_NE(nullptr, cert);
1800 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1801 certData = serializeCertificate(cert.get(), certificateFormat);
1802 }
1803
1804 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1805 auto desCert = deserializeCertificate(certData, certificateFormat);
1806 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001807 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1808 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001809
1810 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1811 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1812
1813 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1814 ASSERT_TRUE(client.setUp(utilsParam));
1815
1816 ASSERT_EQ(OK, trust(&client, server));
1817 ASSERT_EQ(OK, trust(server, &client));
1818
1819 server->start();
1820 client.run();
1821}
1822
1823INSTANTIATE_TEST_CASE_P(
1824 BinderRpc, RpcTransportTlsKeyTest,
1825 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1826 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001827 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1828 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001829 RpcTransportTlsKeyTest::PrintParamInfo);
1830
Steven Morelandc1635952021-04-01 16:20:47 +00001831} // namespace android
1832
1833int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001834 ::testing::InitGoogleTest(&argc, argv);
1835 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001836
Steven Moreland5553ac42020-11-11 02:14:45 +00001837 return RUN_ALL_TESTS();
1838}