blob: 79bd9d4993fc5691755ed5fd1bee70b98523f26a [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
Steven Moreland37aff182021-03-26 02:04:16 +0000915TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000916 if constexpr (!kEnableSharedLibs) {
917 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
918 }
919
Steven Moreland4313d7e2021-07-15 23:41:22 +0000920 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000921
922 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
923 ASSERT_NE(binder, nullptr);
924
925 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
926}
927
928TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000929 if constexpr (!kEnableSharedLibs) {
930 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
931 }
932
Steven Moreland4313d7e2021-07-15 23:41:22 +0000933 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000934
935 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
936 ASSERT_NE(binder, nullptr);
937
938 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
939 ASSERT_NE(ndkBinder, nullptr);
940
941 std::string out;
942 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
943 ASSERT_TRUE(status.isOk()) << status.getDescription();
944 ASSERT_EQ("aoeuaoeu", out);
945}
946
Steven Moreland5553ac42020-11-11 02:14:45 +0000947ssize_t countFds() {
948 DIR* dir = opendir("/proc/self/fd/");
949 if (dir == nullptr) return -1;
950 ssize_t ret = 0;
951 dirent* ent;
952 while ((ent = readdir(dir)) != nullptr) ret++;
953 closedir(dir);
954 return ret;
955}
956
Andrei Homescua858b0e2022-08-01 23:43:09 +0000957TEST_P(BinderRpc, Fds) {
958 if (serverSingleThreaded()) {
959 GTEST_SKIP() << "This test requires multiple threads";
960 }
961
Steven Moreland5553ac42020-11-11 02:14:45 +0000962 ssize_t beforeFds = countFds();
963 ASSERT_GE(beforeFds, 0);
964 {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000965 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +0000966 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
967 }
968 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
969}
970
Steven Morelandda573042021-06-12 01:13:45 +0000971static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -0700972 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +0000973 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +0000974
Andrei Homescu992a4052022-06-28 21:26:18 +0000975 android::base::unique_fd serverFd(
976 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
977 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
978
979 sockaddr_vm serverAddr{
980 .svm_family = AF_VSOCK,
981 .svm_port = vsockPort,
982 .svm_cid = VMADDR_CID_ANY,
983 };
984 int ret = TEMP_FAILURE_RETRY(
985 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
986 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
987 strerror(errno));
988
989 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
990 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
991 strerror(errno));
992
993 // Try to connect to the server using the VMADDR_CID_LOCAL cid
994 // to see if the kernel supports it. It's safe to use a blocking
995 // connect because vsock sockets have a 2 second connection timeout,
996 // and they return ETIMEDOUT after that.
997 android::base::unique_fd connectFd(
998 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
999 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1000 strerror(errno));
1001
1002 bool success = false;
1003 sockaddr_vm connectAddr{
1004 .svm_family = AF_VSOCK,
1005 .svm_port = vsockPort,
1006 .svm_cid = VMADDR_CID_LOCAL,
1007 };
1008 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1009 sizeof(connectAddr)));
1010 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1011 android::base::unique_fd acceptFd;
1012 while (true) {
1013 pollfd pfd[]{
1014 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1015 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1016 };
1017 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1018 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1019
1020 if (pfd[0].revents & POLLIN) {
1021 sockaddr_vm acceptAddr;
1022 socklen_t acceptAddrLen = sizeof(acceptAddr);
1023 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1024 reinterpret_cast<sockaddr*>(&acceptAddr),
1025 &acceptAddrLen, SOCK_CLOEXEC));
1026 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1027 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1028 "Truncated address");
1029
1030 // Store the fd in acceptFd so we keep the connection alive
1031 // while polling connectFd
1032 acceptFd.reset(ret);
1033 }
1034
1035 if (pfd[1].revents & POLLOUT) {
1036 // Connect either succeeded or timed out
1037 int connectErrno;
1038 socklen_t connectErrnoLen = sizeof(connectErrno);
1039 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1040 &connectErrnoLen);
1041 LOG_ALWAYS_FATAL_IF(ret == -1,
1042 "Could not getsockopt() after connect() "
1043 "on non-blocking socket: %s.",
1044 strerror(errno));
1045
1046 // We're done, this is all we wanted
1047 success = connectErrno == 0;
1048 break;
1049 }
1050 }
1051 } else {
1052 success = ret == 0;
1053 }
1054
1055 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1056
1057 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001058}
1059
Yifan Hong1deca4b2021-09-10 16:16:44 -07001060static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001061 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1062 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001063
1064 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001065
1066 static bool hasVsockLoopback = testSupportVsockLoopback();
1067
1068 if (hasVsockLoopback) {
1069 ret.push_back(SocketType::VSOCK);
1070 }
1071
1072 return ret;
1073}
1074
Frederick Mayledc07cf82022-05-26 20:30:12 +00001075static std::vector<uint32_t> testVersions() {
1076 std::vector<uint32_t> versions;
1077 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1078 versions.push_back(i);
1079 }
1080 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1081 return versions;
1082}
1083
Yifan Hong702115c2021-06-24 15:39:18 -07001084INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1085 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001086 ::testing::ValuesIn(RpcSecurityValues()),
1087 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001088 ::testing::ValuesIn(testVersions()),
1089 ::testing::Values(false, true),
1090 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001091 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001092
Yifan Hong702115c2021-06-24 15:39:18 -07001093class BinderRpcServerRootObject
1094 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001095
1096TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1097 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1098 auto setRootObject = [](bool isStrong) -> SetFn {
1099 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1100 };
1101
Yifan Hong702115c2021-06-24 15:39:18 -07001102 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1103 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001104 auto binder1 = sp<BBinder>::make();
1105 IBinder* binderRaw1 = binder1.get();
1106 setRootObject(isStrong1)(server.get(), binder1);
1107 EXPECT_EQ(binderRaw1, server->getRootObject());
1108 binder1.clear();
1109 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1110
1111 auto binder2 = sp<BBinder>::make();
1112 IBinder* binderRaw2 = binder2.get();
1113 setRootObject(isStrong2)(server.get(), binder2);
1114 EXPECT_EQ(binderRaw2, server->getRootObject());
1115 binder2.clear();
1116 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1117}
1118
1119INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001120 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1121 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001122
Yifan Hong1a235852021-05-13 16:07:47 -07001123class OneOffSignal {
1124public:
1125 // If notify() was previously called, or is called within |duration|, return true; else false.
1126 template <typename R, typename P>
1127 bool wait(std::chrono::duration<R, P> duration) {
1128 std::unique_lock<std::mutex> lock(mMutex);
1129 return mCv.wait_for(lock, duration, [this] { return mValue; });
1130 }
1131 void notify() {
1132 std::unique_lock<std::mutex> lock(mMutex);
1133 mValue = true;
1134 lock.unlock();
1135 mCv.notify_all();
1136 }
1137
1138private:
1139 std::mutex mMutex;
1140 std::condition_variable mCv;
1141 bool mValue = false;
1142};
1143
Yifan Hong194acf22021-06-29 18:44:56 -07001144TEST(BinderRpc, Java) {
1145#if !defined(__ANDROID__)
1146 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1147 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1148 "to binderHostDeviceTest. Hence, just disable this test on host.";
1149#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001150 if constexpr (!kEnableKernelIpc) {
1151 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1152 "at build time.";
1153 }
1154
Yifan Hong194acf22021-06-29 18:44:56 -07001155 sp<IServiceManager> sm = defaultServiceManager();
1156 ASSERT_NE(nullptr, sm);
1157 // Any Java service with non-empty getInterfaceDescriptor() would do.
1158 // Let's pick batteryproperties.
1159 auto binder = sm->checkService(String16("batteryproperties"));
1160 ASSERT_NE(nullptr, binder);
1161 auto descriptor = binder->getInterfaceDescriptor();
1162 ASSERT_GE(descriptor.size(), 0);
1163 ASSERT_EQ(OK, binder->pingBinder());
1164
1165 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001166 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001167 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001168 auto socket = rpcServer->releaseServer();
1169
1170 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001171 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1172
Yifan Honge3caaf22022-01-12 14:46:56 -08001173 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1174 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001175 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001176 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1177 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001178 << statusToString(setRpcClientDebugStatus);
1179 GTEST_SKIP();
1180 }
1181
1182 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001183
1184 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001185 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001186 auto rpcBinder = rpcSession->getRootObject();
1187 ASSERT_NE(nullptr, rpcBinder);
1188
1189 ASSERT_EQ(OK, rpcBinder->pingBinder());
1190
1191 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1192 << "getInterfaceDescriptor should not crash system_server";
1193 ASSERT_EQ(OK, rpcBinder->pingBinder());
1194}
1195
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001196class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1197public:
1198 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1199 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1200 std::to_string(std::get<1>(info.param));
1201 }
1202};
1203
1204TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1205 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1206 int sinkFd = sink.get();
1207 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1208 server->setProtocolVersion(std::get<1>(GetParam()));
1209 ASSERT_FALSE(server->hasServer());
1210 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1211 ASSERT_TRUE(server->hasServer());
1212 base::unique_fd retrieved = server->releaseServer();
1213 ASSERT_FALSE(server->hasServer());
1214 ASSERT_EQ(sinkFd, retrieved.get());
1215}
1216
1217TEST_P(BinderRpcServerOnly, Shutdown) {
1218 if constexpr (!kEnableRpcThreads) {
1219 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1220 }
1221
1222 auto addr = allocateSocketAddress();
1223 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1224 server->setProtocolVersion(std::get<1>(GetParam()));
1225 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1226 auto joinEnds = std::make_shared<OneOffSignal>();
1227
1228 // If things are broken and the thread never stops, don't block other tests. Because the thread
1229 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1230 // shared pointers are passed.
1231 std::thread([server, joinEnds] {
1232 server->join();
1233 joinEnds->notify();
1234 }).detach();
1235
1236 bool shutdown = false;
1237 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001238 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001239 if (server->shutdown()) shutdown = true;
1240 }
1241 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1242
1243 ASSERT_TRUE(joinEnds->wait(2s))
1244 << "After server->shutdown() returns true, join() did not stop after 2s";
1245}
1246
Frederick Mayledc07cf82022-05-26 20:30:12 +00001247INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1248 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1249 ::testing::ValuesIn(testVersions())),
1250 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001251
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001252class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001253public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001254 // Only parameterized only server version because `RpcSession` is bypassed
1255 // in the client half of the tests.
1256 using Param =
1257 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001258 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001259
1260 // A server that handles client socket connections.
1261 class Server {
1262 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001263 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1264
Yifan Hong1deca4b2021-09-10 16:16:44 -07001265 explicit Server() {}
1266 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001267 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001268 [[nodiscard]] AssertionResult setUp(
1269 const Param& param,
1270 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001271 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001272 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001273 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001274 switch (socketType) {
1275 case SocketType::PRECONNECTED: {
1276 return AssertionFailure() << "Not supported by this test";
1277 } break;
1278 case SocketType::UNIX: {
1279 auto addr = allocateSocketAddress();
1280 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1281 if (status != OK) {
1282 return AssertionFailure()
1283 << "setupUnixDomainServer: " << statusToString(status);
1284 }
1285 mConnectToServer = [addr] {
1286 return connectTo(UnixSocketAddress(addr.c_str()));
1287 };
1288 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001289 case SocketType::UNIX_BOOTSTRAP: {
1290 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1291 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1292 return AssertionFailure() << "Socketpair() failed";
1293 }
1294 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1295 std::move(bootstrapFdServer));
1296 if (status != OK) {
1297 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1298 << statusToString(status);
1299 }
1300 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1301 mAcceptConnection = &Server::recvmsgServerConnection;
1302 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1303 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001304 case SocketType::UNIX_RAW: {
1305 auto addr = allocateSocketAddress();
1306 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1307 if (status != OK) {
1308 return AssertionFailure()
1309 << "setupRawSocketServer: " << statusToString(status);
1310 }
1311 mConnectToServer = [addr] {
1312 return connectTo(UnixSocketAddress(addr.c_str()));
1313 };
1314 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001315 case SocketType::VSOCK: {
1316 auto port = allocateVsockPort();
1317 auto status = rpcServer->setupVsockServer(port);
1318 if (status != OK) {
1319 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1320 }
1321 mConnectToServer = [port] {
1322 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1323 };
1324 } break;
1325 case SocketType::INET: {
1326 unsigned int port;
1327 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1328 if (status != OK) {
1329 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1330 }
1331 mConnectToServer = [port] {
1332 const char* addr = kLocalInetAddress;
1333 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1334 if (aiStart == nullptr) return base::unique_fd{};
1335 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1336 auto fd = connectTo(
1337 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1338 if (fd.ok()) return fd;
1339 }
1340 ALOGE("None of the socket address resolved for %s:%u can be connected",
1341 addr, port);
1342 return base::unique_fd{};
1343 };
1344 }
1345 }
1346 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001347 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001348 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001349 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1350 mSetup = true;
1351 return AssertionSuccess();
1352 }
1353 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1354 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1355 return mCertVerifier;
1356 }
1357 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1358 void start() {
1359 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1360 mThread = std::make_unique<std::thread>(&Server::run, this);
1361 }
David Brazdil21c887c2022-09-23 12:25:18 +01001362
1363 base::unique_fd acceptServerConnection() {
1364 return base::unique_fd(TEMP_FAILURE_RETRY(
1365 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1366 }
1367
1368 base::unique_fd recvmsgServerConnection() {
1369 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1370 int buf;
1371 iovec iov{&buf, sizeof(buf)};
1372
1373 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1374 int savedErrno = errno;
1375 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1376 }
1377 if (fds.size() != 1) {
1378 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1379 }
1380 return std::move(std::get<base::unique_fd>(fds[0]));
1381 }
1382
Yifan Hong1deca4b2021-09-10 16:16:44 -07001383 void run() {
1384 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1385
1386 std::vector<std::thread> threads;
1387 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001388 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001389 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1390 }
1391
1392 for (auto& thread : threads) thread.join();
1393 }
1394 void handleOne(android::base::unique_fd acceptedFd) {
1395 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001396 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001397 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001398 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001399 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001400 }
Yifan Honge07d2732021-09-13 21:59:14 -07001401 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001402 shutdown();
1403 join();
1404 }
1405 void shutdown() { mFdTrigger->trigger(); }
1406
1407 void setPostConnect(
1408 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1409 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001410 }
1411
1412 private:
1413 std::unique_ptr<std::thread> mThread;
1414 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001415 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001416 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001417 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001418 std::unique_ptr<RpcTransportCtx> mCtx;
1419 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1420 std::make_shared<RpcCertificateVerifierSimple>();
1421 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001422 // The function invoked after connection and handshake. By default, it is
1423 // |defaultPostConnect| that sends |kMessage| to the client.
1424 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1425 Server::defaultPostConnect;
1426
1427 void join() {
1428 if (mThread != nullptr) {
1429 mThread->join();
1430 mThread = nullptr;
1431 }
1432 }
1433
1434 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1435 FdTrigger* fdTrigger) {
1436 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001437 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001438 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001439 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001440 if (status != OK) return AssertionFailure() << statusToString(status);
1441 return AssertionSuccess();
1442 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001443 };
1444
1445 class Client {
1446 public:
1447 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1448 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001449 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001450 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1451 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001452 mFdTrigger = FdTrigger::make();
1453 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1454 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1455 return AssertionSuccess();
1456 }
1457 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1458 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1459 return mCertVerifier;
1460 }
Yifan Hong67519322021-09-13 18:51:16 -07001461 // connect() and do handshake
1462 bool setUpTransport() {
1463 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001464 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001465 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1466 return mClientTransport != nullptr;
1467 }
1468 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1469 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1470 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001471 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001472 status_t readStatus =
1473 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001474 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001475 if (readStatus != OK) {
1476 return AssertionFailure() << statusToString(readStatus);
1477 }
1478 if (readMessage != expectedMessage) {
1479 return AssertionFailure()
1480 << "Expected " << expectedMessage << ", actual " << readMessage;
1481 }
1482 return AssertionSuccess();
1483 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001484 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001485 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001486 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1487 return;
1488 }
1489 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001490 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001491 }
1492
Pawan49d74cb2022-08-03 21:19:11 +00001493 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1494
Yifan Hong1deca4b2021-09-10 16:16:44 -07001495 private:
1496 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001497 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001498 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1499 std::unique_ptr<RpcTransportCtx> mCtx;
1500 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1501 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001502 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001503 };
1504
1505 // Make A trust B.
1506 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001507 static status_t trust(RpcSecurity rpcSecurity,
1508 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1509 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001510 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001511 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1512 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1513 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001514 }
1515
1516 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001517};
1518
1519class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1520public:
1521 using Server = RpcTransportTestUtils::Server;
1522 using Client = RpcTransportTestUtils::Client;
1523 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001524 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001525 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1526 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001527 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001528 return ret;
1529 }
1530 static std::vector<ParamType> getRpcTranportTestParams() {
1531 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001532 for (auto serverVersion : testVersions()) {
1533 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1534 for (auto rpcSecurity : RpcSecurityValues()) {
1535 switch (rpcSecurity) {
1536 case RpcSecurity::RAW: {
1537 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1538 } break;
1539 case RpcSecurity::TLS: {
1540 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1541 serverVersion);
1542 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1543 serverVersion);
1544 } break;
1545 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001546 }
1547 }
1548 }
1549 return ret;
1550 }
1551 template <typename A, typename B>
1552 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001553 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1554 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001555 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1556 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001557 void SetUp() override {
1558 if constexpr (!kEnableRpcThreads) {
1559 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1560 }
1561 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001562};
1563
1564TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001565 auto server = std::make_unique<Server>();
1566 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001567
1568 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001569 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001570
1571 ASSERT_EQ(OK, trust(&client, server));
1572 ASSERT_EQ(OK, trust(server, &client));
1573
1574 server->start();
1575 client.run();
1576}
1577
1578TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001579 auto server = std::make_unique<Server>();
1580 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001581
1582 std::vector<Client> clients;
1583 for (int i = 0; i < 2; i++) {
1584 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001585 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001586 ASSERT_EQ(OK, trust(&client, server));
1587 ASSERT_EQ(OK, trust(server, &client));
1588 }
1589
1590 server->start();
1591 for (auto& client : clients) client.run();
1592}
1593
1594TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001595 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1596 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001597
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001598 auto untrustedServer = std::make_unique<Server>();
1599 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001600
1601 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001602 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001603
1604 ASSERT_EQ(OK, trust(untrustedServer, &client));
1605
1606 untrustedServer->start();
1607
1608 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1609 // the client can't verify the server's identity.
1610 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1611 client.run(handshakeOk);
1612}
1613TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001614 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1615 (void)serverVersion;
1616
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001617 auto validServer = std::make_unique<Server>();
1618 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001620 auto maliciousServer = std::make_unique<Server>();
1621 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001622
1623 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001624 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625
1626 ASSERT_EQ(OK, trust(&client, validServer));
1627 ASSERT_EQ(OK, trust(validServer, &client));
1628 ASSERT_EQ(OK, trust(maliciousServer, &client));
1629
1630 maliciousServer->start();
1631
1632 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1633 // the client can't verify the server's identity.
1634 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1635 client.run(handshakeOk);
1636}
1637
1638TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001639 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1640 (void)serverVersion;
1641
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001642 auto server = std::make_unique<Server>();
1643 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001644
1645 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001646 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001647
1648 ASSERT_EQ(OK, trust(&client, server));
1649
1650 server->start();
1651
1652 // For TLS, Client should be able to verify server's identity, so client should see
1653 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1654 // identity and should drop the connection, so client shouldn't be able to read anything.
1655 bool readOk = rpcSecurity != RpcSecurity::TLS;
1656 client.run(true, readOk);
1657}
1658
1659TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001660 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1661 (void)serverVersion;
1662
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001663 auto server = std::make_unique<Server>();
1664 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001665
1666 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001667 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001668 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001669 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001670
1671 ASSERT_EQ(OK, trust(&validClient, server));
1672 ASSERT_EQ(OK, trust(&maliciousClient, server));
1673
1674 server->start();
1675
1676 // See UntrustedClient.
1677 bool readOk = rpcSecurity != RpcSecurity::TLS;
1678 maliciousClient.run(true, readOk);
1679}
1680
Yifan Hong67519322021-09-13 18:51:16 -07001681TEST_P(RpcTransportTest, Trigger) {
1682 std::string msg2 = ", world!";
1683 std::mutex writeMutex;
1684 std::condition_variable writeCv;
1685 bool shouldContinueWriting = false;
1686 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001687 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001688 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001689 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1690 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001691 if (status != OK) return AssertionFailure() << statusToString(status);
1692
1693 {
1694 std::unique_lock<std::mutex> lock(writeMutex);
1695 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1696 return AssertionFailure() << "write barrier not cleared in time!";
1697 }
1698 }
1699
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001700 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001701 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1702 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001703 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001704 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001705 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001706 << statusToString(status);
1707 return AssertionSuccess();
1708 };
1709
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001710 auto server = std::make_unique<Server>();
1711 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001712
1713 // Set up client
1714 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001715 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001716
1717 // Exchange keys
1718 ASSERT_EQ(OK, trust(&client, server));
1719 ASSERT_EQ(OK, trust(server, &client));
1720
1721 server->setPostConnect(serverPostConnect);
1722
Yifan Hong67519322021-09-13 18:51:16 -07001723 server->start();
1724 // connect() to server and do handshake
1725 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001726 // read the first message. This ensures that server has finished handshake and start handling
1727 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001728 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001729 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1730 // write is on an FdTrigger that has been shut down.
1731 server->shutdown();
1732 // Continues server thread to write the second message.
1733 {
Yifan Hong22211f82021-09-14 12:32:25 -07001734 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001735 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001736 }
Yifan Hong22211f82021-09-14 12:32:25 -07001737 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001738 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001739 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001740 // On the client side, second read fails with DEAD_OBJECT
1741 ASSERT_FALSE(client.readMessage(msg2));
1742}
1743
Pawan49d74cb2022-08-03 21:19:11 +00001744TEST_P(RpcTransportTest, CheckWaitingForRead) {
1745 std::mutex readMutex;
1746 std::condition_variable readCv;
1747 bool shouldContinueReading = false;
1748 // Server will write data on transport once its started
1749 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1750 std::string message(RpcTransportTestUtils::kMessage);
1751 iovec messageIov{message.data(), message.size()};
1752 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1753 std::nullopt, nullptr);
1754 if (status != OK) return AssertionFailure() << statusToString(status);
1755
1756 {
1757 std::unique_lock<std::mutex> lock(readMutex);
1758 shouldContinueReading = true;
1759 lock.unlock();
1760 readCv.notify_all();
1761 }
1762 return AssertionSuccess();
1763 };
1764
1765 // Setup Server and client
1766 auto server = std::make_unique<Server>();
1767 ASSERT_TRUE(server->setUp(GetParam()));
1768
1769 Client client(server->getConnectToServerFn());
1770 ASSERT_TRUE(client.setUp(GetParam()));
1771
1772 ASSERT_EQ(OK, trust(&client, server));
1773 ASSERT_EQ(OK, trust(server, &client));
1774 server->setPostConnect(serverPostConnect);
1775
1776 server->start();
1777 ASSERT_TRUE(client.setUpTransport());
1778 {
1779 // Wait till server writes data
1780 std::unique_lock<std::mutex> lock(readMutex);
1781 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1782 }
1783
1784 // Since there is no read polling here, we will get polling count 0
1785 ASSERT_FALSE(client.isTransportWaiting());
1786 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1787 // Thread should increment polling count, read and decrement polling count
1788 // Again, polling count should be zero here
1789 ASSERT_FALSE(client.isTransportWaiting());
1790
1791 server->shutdown();
1792}
1793
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001795 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001796 RpcTransportTest::PrintParamInfo);
1797
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001798class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001799 : public testing::TestWithParam<
1800 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001801public:
1802 template <typename A, typename B>
1803 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001804 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1805 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001806 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1807 }
1808 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001809 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1810 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1811 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001812 };
1813};
1814
1815TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001816 if constexpr (!kEnableRpcThreads) {
1817 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1818 }
1819
Frederick Mayledc07cf82022-05-26 20:30:12 +00001820 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001821
1822 std::vector<uint8_t> pkeyData, certData;
1823 {
1824 auto pkey = makeKeyPairForSelfSignedCert();
1825 ASSERT_NE(nullptr, pkey);
1826 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1827 ASSERT_NE(nullptr, cert);
1828 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1829 certData = serializeCertificate(cert.get(), certificateFormat);
1830 }
1831
1832 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1833 auto desCert = deserializeCertificate(certData, certificateFormat);
1834 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001835 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1836 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001837
1838 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1839 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1840
1841 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1842 ASSERT_TRUE(client.setUp(utilsParam));
1843
1844 ASSERT_EQ(OK, trust(&client, server));
1845 ASSERT_EQ(OK, trust(server, &client));
1846
1847 server->start();
1848 client.run();
1849}
1850
1851INSTANTIATE_TEST_CASE_P(
1852 BinderRpc, RpcTransportTlsKeyTest,
1853 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1854 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001855 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1856 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001857 RpcTransportTlsKeyTest::PrintParamInfo);
1858
Steven Morelandc1635952021-04-01 16:20:47 +00001859} // namespace android
1860
1861int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001862 ::testing::InitGoogleTest(&argc, argv);
1863 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001864
Steven Moreland5553ac42020-11-11 02:14:45 +00001865 return RUN_ALL_TESTS();
1866}