blob: 9be5b879d433ebf8052c3417ee62b648884c1805 [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
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000032#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000033
Yifan Hong1a235852021-05-13 16:07:47 -070034using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070035using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070036using testing::AssertionFailure;
37using testing::AssertionResult;
38using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070039
Steven Moreland5553ac42020-11-11 02:14:45 +000040namespace android {
41
Andrei Homescu12106de2022-04-27 04:42:21 +000042#ifdef BINDER_TEST_NO_SHARED_LIBS
43constexpr bool kEnableSharedLibs = false;
44#else
45constexpr bool kEnableSharedLibs = true;
46#endif
47
Frederick Maylea12b0962022-06-25 01:13:22 +000048static std::string WaitStatusToString(int wstatus) {
49 if (WIFEXITED(wstatus)) {
50 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
51 }
52 if (WIFSIGNALED(wstatus)) {
53 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
54 }
55 return base::StringPrintf("unexpected state %d", wstatus);
56}
57
Steven Moreland276d8df2022-09-28 23:56:39 +000058static void debugBacktrace(pid_t pid) {
59 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
60 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
61}
62
Steven Moreland5553ac42020-11-11 02:14:45 +000063class Process {
64public:
Andrei Homescu96834632022-10-14 00:49:49 +000065 Process(Process&& other)
66 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
67 mReadEnd(std::move(other.mReadEnd)),
68 mWriteEnd(std::move(other.mWriteEnd)) {
69 // The default move constructor doesn't clear mPid after moving it,
70 // which we need to do because the destructor checks for mPid!=0
71 mPid = other.mPid;
72 other.mPid = 0;
73 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070074 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
75 android::base::borrowed_fd /* readEnd */)>& f) {
76 android::base::unique_fd childWriteEnd;
77 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000078 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
79 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000080 if (0 == (mPid = fork())) {
81 // racey: assume parent doesn't crash before this is set
82 prctl(PR_SET_PDEATHSIG, SIGHUP);
83
Yifan Hong1deca4b2021-09-10 16:16:44 -070084 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000085
86 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000087 }
88 }
89 ~Process() {
90 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +000091 int wstatus;
92 waitpid(mPid, &wstatus, 0);
93 if (mCustomExitStatusCheck) {
94 mCustomExitStatusCheck(wstatus);
95 } else {
96 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
97 << "server process failed: " << WaitStatusToString(wstatus);
98 }
Steven Moreland5553ac42020-11-11 02:14:45 +000099 }
100 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700101 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700102 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000103
Frederick Maylea12b0962022-06-25 01:13:22 +0000104 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
105 mCustomExitStatusCheck = std::move(f);
106 }
107
Frederick Mayle69a0c992022-05-26 20:38:39 +0000108 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
109 void terminate() { kill(mPid, SIGTERM); }
110
Steven Moreland276d8df2022-09-28 23:56:39 +0000111 pid_t getPid() { return mPid; }
112
Steven Moreland5553ac42020-11-11 02:14:45 +0000113private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000114 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000115 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700116 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700117 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000118};
119
120static std::string allocateSocketAddress() {
121 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000122 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700123 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
124 unlink(ret.c_str());
125 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000126};
127
Steven Morelandda573042021-06-12 01:13:45 +0000128static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000129 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000130 return vsockPort++;
131}
132
Alice Wang893a9912022-10-24 10:44:09 +0000133static base::unique_fd initUnixSocket(std::string addr) {
134 auto socket_addr = UnixSocketAddress(addr.c_str());
135 base::unique_fd fd(
136 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
137 CHECK(fd.ok());
138 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
139 return fd;
140}
141
Andrei Homescu96834632022-10-14 00:49:49 +0000142// Destructors need to be defined, even if pure virtual
143ProcessSession::~ProcessSession() {}
144
145class LinuxProcessSession : public ProcessSession {
146public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000147 // reference to process hosting a socket server
148 Process host;
149
Andrei Homescu96834632022-10-14 00:49:49 +0000150 LinuxProcessSession(LinuxProcessSession&&) = default;
151 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
152 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 for (auto& session : sessions) {
154 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000155 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000156
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157 for (auto& info : sessions) {
158 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000159
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000160 EXPECT_NE(nullptr, session);
161 EXPECT_NE(nullptr, session->state());
162 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000163
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 wp<RpcSession> weakSession = session;
165 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000166
Steven Moreland57042712022-10-04 23:56:45 +0000167 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
168 // the object should not actually be promotable. By looping, we distinguish a race here
169 // from a bug causing the object to not be promotable.
170 for (size_t i = 0; i < 3; i++) {
171 sp<RpcSession> strongSession = weakSession.promote();
172 EXPECT_EQ(nullptr, strongSession)
173 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
174 "Leaked sess: ")
175 << strongSession->getStrongCount() << " checked time " << i;
176
177 if (strongSession != nullptr) {
178 sleep(1);
179 }
180 }
Steven Moreland736664b2021-05-01 04:27:25 +0000181 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000182 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000183
Andrei Homescu96834632022-10-14 00:49:49 +0000184 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
185 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000186 }
Andrei Homescu96834632022-10-14 00:49:49 +0000187
188 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000189};
190
Yifan Hong1deca4b2021-09-10 16:16:44 -0700191static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700192 base::unique_fd serverFd(
193 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
194 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700195 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
196 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700197
198 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
199 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700200 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
201 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700202 }
203 return serverFd;
204}
205
David Brazdil21c887c2022-09-23 12:25:18 +0100206static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
207 base::unique_fd sockClient, sockServer;
208 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
209 int savedErrno = errno;
210 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
211 }
212
213 int zero = 0;
214 iovec iov{&zero, sizeof(zero)};
215 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
216 fds.emplace_back(std::move(sockServer));
217
218 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
219 int savedErrno = errno;
220 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
221 }
222 return std::move(sockClient);
223}
224
Andrei Homescu96834632022-10-14 00:49:49 +0000225std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
226 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
227 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
228 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
229 if (singleThreaded) {
230 ret += "_single_threaded";
231 }
232 if (noKernel) {
233 ret += "_no_kernel";
234 }
235 return ret;
236}
Andrei Homescu2a298012022-06-15 01:08:54 +0000237
Andrei Homescu96834632022-10-14 00:49:49 +0000238// This creates a new process serving an interface on a certain number of
239// threads.
240std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
241 const BinderRpcOptions& options) {
242 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000243
Andrei Homescu96834632022-10-14 00:49:49 +0000244 SocketType socketType = std::get<0>(GetParam());
245 RpcSecurity rpcSecurity = std::get<1>(GetParam());
246 uint32_t clientVersion = std::get<2>(GetParam());
247 uint32_t serverVersion = std::get<3>(GetParam());
248 bool singleThreaded = std::get<4>(GetParam());
249 bool noKernel = std::get<5>(GetParam());
250
251 std::string path = android::base::GetExecutableDirectory();
252 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
253 singleThreaded ? "_single_threaded" : "",
254 noKernel ? "_no_kernel" : "");
255
Alice Wang1ef010b2022-11-14 09:09:25 +0000256 base::unique_fd bootstrapClientFd, socketFd;
257
Alice Wang893a9912022-10-24 10:44:09 +0000258 auto addr = allocateSocketAddress();
259 // Initializes the socket before the fork/exec.
260 if (socketType == SocketType::UNIX_RAW) {
261 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000262 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
263 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
264 // This is because we cannot pass ParcelFileDescriptor over a pipe.
265 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
266 int savedErrno = errno;
267 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
268 }
Alice Wang893a9912022-10-24 10:44:09 +0000269 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000270
Andrei Homescu96834632022-10-14 00:49:49 +0000271 auto ret = std::make_unique<LinuxProcessSession>(
272 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
273 auto writeFd = std::to_string(writeEnd.get());
274 auto readFd = std::to_string(readEnd.get());
275 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
276 NULL);
277 }));
278
279 BinderRpcTestServerConfig serverConfig;
280 serverConfig.numThreads = options.numThreads;
281 serverConfig.socketType = static_cast<int32_t>(socketType);
282 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
283 serverConfig.serverVersion = serverVersion;
284 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000285 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000286 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000287 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
288 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
289 static_cast<int32_t>(mode));
290 }
291 writeToFd(ret->host.writeEnd(), serverConfig);
292
293 std::vector<sp<RpcSession>> sessions;
294 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
295 for (size_t i = 0; i < options.numSessions; i++) {
296 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
David Brazdil21c887c2022-09-23 12:25:18 +0100297 }
298
Andrei Homescu96834632022-10-14 00:49:49 +0000299 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
300 BinderRpcTestClientInfo clientInfo;
301 for (const auto& session : sessions) {
302 auto& parcelableCert = clientInfo.certs.emplace_back();
303 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
304 }
305 writeToFd(ret->host.writeEnd(), clientInfo);
306
307 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
308 if (socketType == SocketType::INET) {
309 CHECK_NE(0, serverInfo.port);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000310 }
311
Andrei Homescu96834632022-10-14 00:49:49 +0000312 if (rpcSecurity == RpcSecurity::TLS) {
313 const auto& serverCert = serverInfo.cert.data;
314 CHECK_EQ(OK,
315 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700316 }
317
Andrei Homescu96834632022-10-14 00:49:49 +0000318 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000319
Andrei Homescu96834632022-10-14 00:49:49 +0000320 for (const auto& session : sessions) {
321 CHECK(session->setProtocolVersion(clientVersion));
322 session->setMaxIncomingThreads(options.numIncomingConnections);
323 session->setMaxOutgoingThreads(options.numOutgoingConnections);
324 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000325
Andrei Homescu96834632022-10-14 00:49:49 +0000326 switch (socketType) {
327 case SocketType::PRECONNECTED:
328 status = session->setupPreconnectedClient({}, [=]() {
329 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
330 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000331 break;
Alice Wang893a9912022-10-24 10:44:09 +0000332 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000333 case SocketType::UNIX:
334 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
335 break;
336 case SocketType::UNIX_BOOTSTRAP:
337 status = session->setupUnixDomainSocketBootstrapClient(
338 base::unique_fd(dup(bootstrapClientFd.get())));
339 break;
340 case SocketType::VSOCK:
341 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
342 break;
343 case SocketType::INET:
344 status = session->setupInetClient("127.0.0.1", serverInfo.port);
345 break;
346 default:
347 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000348 }
Andrei Homescu96834632022-10-14 00:49:49 +0000349 if (options.allowConnectFailure && status != OK) {
350 ret->sessions.clear();
351 break;
352 }
353 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
354 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000355 }
Andrei Homescu96834632022-10-14 00:49:49 +0000356 return ret;
357}
Steven Morelandc1635952021-04-01 16:20:47 +0000358
Andrei Homescua858b0e2022-08-01 23:43:09 +0000359TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
360 if (clientOrServerSingleThreaded()) {
361 GTEST_SKIP() << "This test requires multiple threads";
362 }
363
Steven Moreland5553ac42020-11-11 02:14:45 +0000364 constexpr size_t kNumThreads = 10;
365
Steven Moreland4313d7e2021-07-15 23:41:22 +0000366 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000367
368 EXPECT_OK(proc.rootIface->lock());
369
370 // block all but one thread taking locks
371 std::vector<std::thread> ts;
372 for (size_t i = 0; i < kNumThreads - 1; i++) {
373 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
374 }
375
Steven Morelandd6d816f2022-12-23 01:37:17 +0000376 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000377
378 // other calls still work
379 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
380
Steven Morelandd6d816f2022-12-23 01:37:17 +0000381 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000382 size_t epochMsBefore = epochMillis();
383 // after this, we should never see a response within this time
384 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
385
386 // this call should be blocked for blockTimeMs
387 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
388
389 size_t epochMsAfter = epochMillis();
390 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
391
392 for (auto& t : ts) t.join();
393}
394
Andrei Homescu96834632022-10-14 00:49:49 +0000395static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
396 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000397 size_t epochMsBefore = epochMillis();
398
399 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700400 for (size_t i = 0; i < numCalls; i++) {
401 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 }
403
404 for (auto& t : ts) t.join();
405
406 size_t epochMsAfter = epochMillis();
407
Yifan Hong1f44f982021-10-08 17:16:47 -0700408 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000409
410 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700411 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
412}
413
Andrei Homescua858b0e2022-08-01 23:43:09 +0000414TEST_P(BinderRpc, ThreadPoolOverSaturated) {
415 if (clientOrServerSingleThreaded()) {
416 GTEST_SKIP() << "This test requires multiple threads";
417 }
418
Yifan Hong1f44f982021-10-08 17:16:47 -0700419 constexpr size_t kNumThreads = 10;
420 constexpr size_t kNumCalls = kNumThreads + 3;
421 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
422 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
423}
424
Andrei Homescua858b0e2022-08-01 23:43:09 +0000425TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
426 if (clientOrServerSingleThreaded()) {
427 GTEST_SKIP() << "This test requires multiple threads";
428 }
429
Yifan Hong1f44f982021-10-08 17:16:47 -0700430 constexpr size_t kNumThreads = 20;
431 constexpr size_t kNumOutgoingConnections = 10;
432 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
433 auto proc = createRpcTestSocketServerProcess(
434 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
435 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000436}
437
Andrei Homescua858b0e2022-08-01 23:43:09 +0000438TEST_P(BinderRpc, ThreadingStressTest) {
439 if (clientOrServerSingleThreaded()) {
440 GTEST_SKIP() << "This test requires multiple threads";
441 }
442
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 constexpr size_t kNumClientThreads = 10;
444 constexpr size_t kNumServerThreads = 10;
445 constexpr size_t kNumCalls = 100;
446
Steven Moreland4313d7e2021-07-15 23:41:22 +0000447 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000448
449 std::vector<std::thread> threads;
450 for (size_t i = 0; i < kNumClientThreads; i++) {
451 threads.push_back(std::thread([&] {
452 for (size_t j = 0; j < kNumCalls; j++) {
453 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000454 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 EXPECT_EQ(proc.rootBinder, out);
456 }
457 }));
458 }
459
460 for (auto& t : threads) t.join();
461}
462
Steven Moreland925ba0a2021-09-17 18:06:32 -0700463static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
464 std::vector<std::thread> threads;
465 for (size_t i = 0; i < threadCount; i++) {
466 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
467 }
468 for (auto& t : threads) t.join();
469}
470
Andrei Homescua858b0e2022-08-01 23:43:09 +0000471TEST_P(BinderRpc, OnewayStressTest) {
472 if (clientOrServerSingleThreaded()) {
473 GTEST_SKIP() << "This test requires multiple threads";
474 }
475
Steven Morelandc6046982021-04-20 00:49:42 +0000476 constexpr size_t kNumClientThreads = 10;
477 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700478 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000479
Steven Moreland4313d7e2021-07-15 23:41:22 +0000480 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000481
482 std::vector<std::thread> threads;
483 for (size_t i = 0; i < kNumClientThreads; i++) {
484 threads.push_back(std::thread([&] {
485 for (size_t j = 0; j < kNumCalls; j++) {
486 EXPECT_OK(proc.rootIface->sendString("a"));
487 }
Steven Morelandc6046982021-04-20 00:49:42 +0000488 }));
489 }
490
491 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700492
493 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000494}
495
Frederick Mayleb0221d12022-10-03 23:10:53 +0000496TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
497 if (!supportsFdTransport()) {
498 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
499 }
500 if (clientOrServerSingleThreaded()) {
501 GTEST_SKIP() << "This test requires multiple threads";
502 }
503
504 // This test forces a oneway transaction to be queued by issuing two
505 // `blockingSendFdOneway` calls, then drains the queue by issuing two
506 // `blockingRecvFd` calls.
507 //
508 // For more details about the queuing semantics see
509 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
510
511 auto proc = createRpcTestSocketServerProcess({
512 .numThreads = 3,
513 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
514 .serverSupportedFileDescriptorTransportModes =
515 {RpcSession::FileDescriptorTransportMode::UNIX},
516 });
517
518 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
519 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
520 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
521 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
522
523 android::os::ParcelFileDescriptor fdA;
524 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
525 std::string result;
526 CHECK(android::base::ReadFdToString(fdA.get(), &result));
527 EXPECT_EQ(result, "a");
528
529 android::os::ParcelFileDescriptor fdB;
530 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
531 CHECK(android::base::ReadFdToString(fdB.get(), &result));
532 EXPECT_EQ(result, "b");
533}
534
Andrei Homescua858b0e2022-08-01 23:43:09 +0000535TEST_P(BinderRpc, OnewayCallQueueing) {
536 if (clientOrServerSingleThreaded()) {
537 GTEST_SKIP() << "This test requires multiple threads";
538 }
539
Steven Moreland5553ac42020-11-11 02:14:45 +0000540 constexpr size_t kNumSleeps = 10;
541 constexpr size_t kNumExtraServerThreads = 4;
542 constexpr size_t kSleepMs = 50;
543
544 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000545 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000546
547 EXPECT_OK(proc.rootIface->lock());
548
Steven Moreland1c678802021-09-17 16:48:47 -0700549 size_t epochMsBefore = epochMillis();
550
551 // all these *Async commands should be queued on the server sequentially,
552 // even though there are multiple threads.
553 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 proc.rootIface->sleepMsAsync(kSleepMs);
555 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000556 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
557
Steven Moreland1c678802021-09-17 16:48:47 -0700558 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700560
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 size_t epochMsAfter = epochMillis();
562
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000563 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000564
Steven Moreland925ba0a2021-09-17 18:06:32 -0700565 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000566}
567
Andrei Homescua858b0e2022-08-01 23:43:09 +0000568TEST_P(BinderRpc, OnewayCallExhaustion) {
569 if (clientOrServerSingleThreaded()) {
570 GTEST_SKIP() << "This test requires multiple threads";
571 }
572
Steven Morelandd45be622021-06-04 02:19:37 +0000573 constexpr size_t kNumClients = 2;
574 constexpr size_t kTooLongMs = 1000;
575
Steven Moreland4313d7e2021-07-15 23:41:22 +0000576 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000577
578 // Build up oneway calls on the second session to make sure it terminates
579 // and shuts down. The first session should be unaffected (proc destructor
580 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000581 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000582
583 std::vector<std::thread> threads;
584 for (size_t i = 0; i < kNumClients; i++) {
585 // one of these threads will get stuck queueing a transaction once the
586 // socket fills up, the other will be able to fill up transactions on
587 // this object
588 threads.push_back(std::thread([&] {
589 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
590 }
591 }));
592 }
593 for (auto& t : threads) t.join();
594
595 Status status = iface->sleepMsAsync(kTooLongMs);
596 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
597
Steven Moreland798e0d12021-07-14 23:19:25 +0000598 // now that it has died, wait for the remote session to shutdown
599 std::vector<int32_t> remoteCounts;
600 do {
601 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
602 } while (remoteCounts.size() == kNumClients);
603
Steven Morelandd45be622021-06-04 02:19:37 +0000604 // the second session should be shutdown in the other process by the time we
605 // are able to join above (it'll only be hung up once it finishes processing
606 // any pending commands). We need to erase this session from the record
607 // here, so that the destructor for our session won't check that this
608 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000609 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000610}
611
Devin Moore66d5b7a2022-07-07 21:42:10 +0000612TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000613 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000614 GTEST_SKIP() << "This test requires multiple threads";
615 }
616 class MyDeathRec : public IBinder::DeathRecipient {
617 public:
618 void binderDied(const wp<IBinder>& /* who */) override {
619 dead = true;
620 mCv.notify_one();
621 }
622 std::mutex mMtx;
623 std::condition_variable mCv;
624 bool dead = false;
625 };
626
627 // Death recipient needs to have an incoming connection to be called
628 auto proc = createRpcTestSocketServerProcess(
629 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
630
631 auto dr = sp<MyDeathRec>::make();
632 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
633
634 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
635 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
636 }
637
638 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000639 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000640
641 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000642 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000643 proc.expectAlreadyShutdown = true;
644}
645
646TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000647 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000648 GTEST_SKIP() << "This test requires multiple threads";
649 }
650 class MyDeathRec : public IBinder::DeathRecipient {
651 public:
652 void binderDied(const wp<IBinder>& /* who */) override {
653 dead = true;
654 mCv.notify_one();
655 }
656 std::mutex mMtx;
657 std::condition_variable mCv;
658 bool dead = false;
659 };
660
661 // Death recipient needs to have an incoming connection to be called
662 auto proc = createRpcTestSocketServerProcess(
663 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
664
665 auto dr = sp<MyDeathRec>::make();
666 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
667
668 // Explicitly calling shutDownAndWait will cause the death recipients
669 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000670 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000671
672 std::unique_lock<std::mutex> lock(dr->mMtx);
673 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000674 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000675 }
676 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
677
Andrei Homescu96834632022-10-14 00:49:49 +0000678 proc.proc->terminate();
679 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000680 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
681 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
682 });
683 proc.expectAlreadyShutdown = true;
684}
685
686TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
687 class MyDeathRec : public IBinder::DeathRecipient {
688 public:
689 void binderDied(const wp<IBinder>& /* who */) override {}
690 };
691
692 auto proc = createRpcTestSocketServerProcess(
693 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
694
695 auto dr = sp<MyDeathRec>::make();
696 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
697 "Cannot register a DeathRecipient without any incoming connections.");
698}
699
700TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000701 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000702 GTEST_SKIP() << "This test requires multiple threads";
703 }
704 class MyDeathRec : public IBinder::DeathRecipient {
705 public:
706 void binderDied(const wp<IBinder>& /* who */) override {
707 GTEST_FAIL() << "This should not be called after unlinkToDeath";
708 }
709 };
710
711 // Death recipient needs to have an incoming connection to be called
712 auto proc = createRpcTestSocketServerProcess(
713 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
714
715 auto dr = sp<MyDeathRec>::make();
716 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
717 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
718
719 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
720 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
721 }
722
723 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000724 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000725 proc.expectAlreadyShutdown = true;
726}
727
Steven Morelandc1635952021-04-01 16:20:47 +0000728TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000729 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000730 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000731
732 // make sure there is some state during crash
733 // 1. we hold their binder
734 sp<IBinderRpcSession> session;
735 EXPECT_OK(proc.rootIface->openSession("happy", &session));
736 // 2. they hold our binder
737 sp<IBinder> binder = new BBinder();
738 EXPECT_OK(proc.rootIface->holdBinder(binder));
739
740 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
741 << "Do death cleanup: " << doDeathCleanup;
742
Andrei Homescu96834632022-10-14 00:49:49 +0000743 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000744 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
745 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
746 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000747 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000748 }
749}
750
Steven Morelandd7302072021-05-15 01:32:04 +0000751TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000752 // This test only works if the current process shared the internal state of
753 // ProcessState with the service across the call to fork(). Both the static
754 // libraries and libbinder.so have their own separate copies of all the
755 // globals, so the test only works when the test client and service both use
756 // libbinder.so (when using static libraries, even a client and service
757 // using the same kind of static library should have separate copies of the
758 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000759 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000760 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
761 "at build time.";
762 }
763
Steven Moreland4313d7e2021-07-15 23:41:22 +0000764 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000765
Andrei Homescu2a298012022-06-15 01:08:54 +0000766 // we can't allocate IPCThreadState so actually the first time should
767 // succeed :(
768 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000769
770 // second time! we catch the error :)
771 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
772
Andrei Homescu96834632022-10-14 00:49:49 +0000773 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000774 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
775 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
776 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000777 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000778}
779
Frederick Mayle69a0c992022-05-26 20:38:39 +0000780TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
781 auto proc = createRpcTestSocketServerProcess({
782 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
783 .serverSupportedFileDescriptorTransportModes =
784 {RpcSession::FileDescriptorTransportMode::UNIX},
785 .allowConnectFailure = true,
786 });
Andrei Homescu96834632022-10-14 00:49:49 +0000787 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
788 proc.proc->terminate();
789 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000790 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
791 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
792 });
793 proc.expectAlreadyShutdown = true;
794}
795
796TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
797 auto proc = createRpcTestSocketServerProcess({
798 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
799 .serverSupportedFileDescriptorTransportModes =
800 {RpcSession::FileDescriptorTransportMode::NONE},
801 .allowConnectFailure = true,
802 });
Andrei Homescu96834632022-10-14 00:49:49 +0000803 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
804 proc.proc->terminate();
805 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000806 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
807 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
808 });
809 proc.expectAlreadyShutdown = true;
810}
811
812TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
813 auto proc = createRpcTestSocketServerProcess({
814 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
815 .serverSupportedFileDescriptorTransportModes =
816 {RpcSession::FileDescriptorTransportMode::NONE,
817 RpcSession::FileDescriptorTransportMode::UNIX},
818 });
819
820 android::os::ParcelFileDescriptor out;
821 auto status = proc.rootIface->echoAsFile("hello", &out);
822 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
823}
824
825TEST_P(BinderRpc, ReceiveFile) {
826 auto proc = createRpcTestSocketServerProcess({
827 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
828 .serverSupportedFileDescriptorTransportModes =
829 {RpcSession::FileDescriptorTransportMode::UNIX},
830 });
831
832 android::os::ParcelFileDescriptor out;
833 auto status = proc.rootIface->echoAsFile("hello", &out);
834 if (!supportsFdTransport()) {
835 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
836 return;
837 }
838 ASSERT_TRUE(status.isOk()) << status;
839
840 std::string result;
841 CHECK(android::base::ReadFdToString(out.get(), &result));
842 EXPECT_EQ(result, "hello");
843}
844
845TEST_P(BinderRpc, SendFiles) {
846 auto proc = createRpcTestSocketServerProcess({
847 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
848 .serverSupportedFileDescriptorTransportModes =
849 {RpcSession::FileDescriptorTransportMode::UNIX},
850 });
851
852 std::vector<android::os::ParcelFileDescriptor> files;
853 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
854 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
855 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
856 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
857
858 android::os::ParcelFileDescriptor out;
859 auto status = proc.rootIface->concatFiles(files, &out);
860 if (!supportsFdTransport()) {
861 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
862 return;
863 }
864 ASSERT_TRUE(status.isOk()) << status;
865
866 std::string result;
867 CHECK(android::base::ReadFdToString(out.get(), &result));
868 EXPECT_EQ(result, "123abcd");
869}
870
871TEST_P(BinderRpc, SendMaxFiles) {
872 if (!supportsFdTransport()) {
873 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
874 }
875
876 auto proc = createRpcTestSocketServerProcess({
877 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
878 .serverSupportedFileDescriptorTransportModes =
879 {RpcSession::FileDescriptorTransportMode::UNIX},
880 });
881
882 std::vector<android::os::ParcelFileDescriptor> files;
883 for (int i = 0; i < 253; i++) {
884 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
885 }
886
887 android::os::ParcelFileDescriptor out;
888 auto status = proc.rootIface->concatFiles(files, &out);
889 ASSERT_TRUE(status.isOk()) << status;
890
891 std::string result;
892 CHECK(android::base::ReadFdToString(out.get(), &result));
893 EXPECT_EQ(result, std::string(253, 'a'));
894}
895
896TEST_P(BinderRpc, SendTooManyFiles) {
897 if (!supportsFdTransport()) {
898 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
899 }
900
901 auto proc = createRpcTestSocketServerProcess({
902 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
903 .serverSupportedFileDescriptorTransportModes =
904 {RpcSession::FileDescriptorTransportMode::UNIX},
905 });
906
907 std::vector<android::os::ParcelFileDescriptor> files;
908 for (int i = 0; i < 254; i++) {
909 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
910 }
911
912 android::os::ParcelFileDescriptor out;
913 auto status = proc.rootIface->concatFiles(files, &out);
914 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
915}
916
Andrei Homescufc221502022-10-08 03:51:17 +0000917TEST_P(BinderRpc, AppendInvalidFd) {
918 auto proc = createRpcTestSocketServerProcess({
919 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
920 .serverSupportedFileDescriptorTransportModes =
921 {RpcSession::FileDescriptorTransportMode::UNIX},
922 });
923
924 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
925 ASSERT_NE(badFd, -1);
926
927 // Close the file descriptor so it becomes invalid for dup
928 close(badFd);
929
930 Parcel p1;
931 p1.markForBinder(proc.rootBinder);
932 p1.writeInt32(3);
933 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
934
935 Parcel pRaw;
936 pRaw.markForBinder(proc.rootBinder);
937 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
938
939 pRaw.setDataPosition(0);
940 EXPECT_EQ(3, pRaw.readInt32());
941 ASSERT_EQ(-1, pRaw.readFileDescriptor());
942}
943
Steven Moreland37aff182021-03-26 02:04:16 +0000944TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000945 if constexpr (!kEnableSharedLibs) {
946 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
947 }
948
Steven Moreland4313d7e2021-07-15 23:41:22 +0000949 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000950
951 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
952 ASSERT_NE(binder, nullptr);
953
954 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
955}
956
957TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000958 if constexpr (!kEnableSharedLibs) {
959 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
960 }
961
Steven Moreland4313d7e2021-07-15 23:41:22 +0000962 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +0000963
964 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
965 ASSERT_NE(binder, nullptr);
966
967 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
968 ASSERT_NE(ndkBinder, nullptr);
969
970 std::string out;
971 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
972 ASSERT_TRUE(status.isOk()) << status.getDescription();
973 ASSERT_EQ("aoeuaoeu", out);
974}
975
Steven Moreland5553ac42020-11-11 02:14:45 +0000976ssize_t countFds() {
977 DIR* dir = opendir("/proc/self/fd/");
978 if (dir == nullptr) return -1;
979 ssize_t ret = 0;
980 dirent* ent;
981 while ((ent = readdir(dir)) != nullptr) ret++;
982 closedir(dir);
983 return ret;
984}
985
Andrei Homescua858b0e2022-08-01 23:43:09 +0000986TEST_P(BinderRpc, Fds) {
987 if (serverSingleThreaded()) {
988 GTEST_SKIP() << "This test requires multiple threads";
989 }
990
Steven Moreland5553ac42020-11-11 02:14:45 +0000991 ssize_t beforeFds = countFds();
992 ASSERT_GE(beforeFds, 0);
993 {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000994 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +0000995 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
996 }
997 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
998}
999
Steven Morelandda573042021-06-12 01:13:45 +00001000static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001001 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001002 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001003
Andrei Homescu992a4052022-06-28 21:26:18 +00001004 android::base::unique_fd serverFd(
1005 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1006 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1007
1008 sockaddr_vm serverAddr{
1009 .svm_family = AF_VSOCK,
1010 .svm_port = vsockPort,
1011 .svm_cid = VMADDR_CID_ANY,
1012 };
1013 int ret = TEMP_FAILURE_RETRY(
1014 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1015 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1016 strerror(errno));
1017
1018 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1019 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1020 strerror(errno));
1021
1022 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1023 // to see if the kernel supports it. It's safe to use a blocking
1024 // connect because vsock sockets have a 2 second connection timeout,
1025 // and they return ETIMEDOUT after that.
1026 android::base::unique_fd connectFd(
1027 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1028 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1029 strerror(errno));
1030
1031 bool success = false;
1032 sockaddr_vm connectAddr{
1033 .svm_family = AF_VSOCK,
1034 .svm_port = vsockPort,
1035 .svm_cid = VMADDR_CID_LOCAL,
1036 };
1037 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1038 sizeof(connectAddr)));
1039 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1040 android::base::unique_fd acceptFd;
1041 while (true) {
1042 pollfd pfd[]{
1043 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1044 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1045 };
1046 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1047 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1048
1049 if (pfd[0].revents & POLLIN) {
1050 sockaddr_vm acceptAddr;
1051 socklen_t acceptAddrLen = sizeof(acceptAddr);
1052 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1053 reinterpret_cast<sockaddr*>(&acceptAddr),
1054 &acceptAddrLen, SOCK_CLOEXEC));
1055 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1056 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1057 "Truncated address");
1058
1059 // Store the fd in acceptFd so we keep the connection alive
1060 // while polling connectFd
1061 acceptFd.reset(ret);
1062 }
1063
1064 if (pfd[1].revents & POLLOUT) {
1065 // Connect either succeeded or timed out
1066 int connectErrno;
1067 socklen_t connectErrnoLen = sizeof(connectErrno);
1068 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1069 &connectErrnoLen);
1070 LOG_ALWAYS_FATAL_IF(ret == -1,
1071 "Could not getsockopt() after connect() "
1072 "on non-blocking socket: %s.",
1073 strerror(errno));
1074
1075 // We're done, this is all we wanted
1076 success = connectErrno == 0;
1077 break;
1078 }
1079 }
1080 } else {
1081 success = ret == 0;
1082 }
1083
1084 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1085
1086 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001087}
1088
Yifan Hong1deca4b2021-09-10 16:16:44 -07001089static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001090 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1091 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001092
1093 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001094
1095 static bool hasVsockLoopback = testSupportVsockLoopback();
1096
1097 if (hasVsockLoopback) {
1098 ret.push_back(SocketType::VSOCK);
1099 }
1100
1101 return ret;
1102}
1103
Yifan Hong702115c2021-06-24 15:39:18 -07001104INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1105 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001106 ::testing::ValuesIn(RpcSecurityValues()),
1107 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001108 ::testing::ValuesIn(testVersions()),
1109 ::testing::Values(false, true),
1110 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001111 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001112
Yifan Hong702115c2021-06-24 15:39:18 -07001113class BinderRpcServerRootObject
1114 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001115
1116TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1117 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1118 auto setRootObject = [](bool isStrong) -> SetFn {
1119 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1120 };
1121
Yifan Hong702115c2021-06-24 15:39:18 -07001122 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1123 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001124 auto binder1 = sp<BBinder>::make();
1125 IBinder* binderRaw1 = binder1.get();
1126 setRootObject(isStrong1)(server.get(), binder1);
1127 EXPECT_EQ(binderRaw1, server->getRootObject());
1128 binder1.clear();
1129 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1130
1131 auto binder2 = sp<BBinder>::make();
1132 IBinder* binderRaw2 = binder2.get();
1133 setRootObject(isStrong2)(server.get(), binder2);
1134 EXPECT_EQ(binderRaw2, server->getRootObject());
1135 binder2.clear();
1136 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1137}
1138
1139INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001140 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1141 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001142
Yifan Hong1a235852021-05-13 16:07:47 -07001143class OneOffSignal {
1144public:
1145 // If notify() was previously called, or is called within |duration|, return true; else false.
1146 template <typename R, typename P>
1147 bool wait(std::chrono::duration<R, P> duration) {
1148 std::unique_lock<std::mutex> lock(mMutex);
1149 return mCv.wait_for(lock, duration, [this] { return mValue; });
1150 }
1151 void notify() {
1152 std::unique_lock<std::mutex> lock(mMutex);
1153 mValue = true;
1154 lock.unlock();
1155 mCv.notify_all();
1156 }
1157
1158private:
1159 std::mutex mMutex;
1160 std::condition_variable mCv;
1161 bool mValue = false;
1162};
1163
Yifan Hong194acf22021-06-29 18:44:56 -07001164TEST(BinderRpc, Java) {
1165#if !defined(__ANDROID__)
1166 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1167 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1168 "to binderHostDeviceTest. Hence, just disable this test on host.";
1169#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001170 if constexpr (!kEnableKernelIpc) {
1171 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1172 "at build time.";
1173 }
1174
Yifan Hong194acf22021-06-29 18:44:56 -07001175 sp<IServiceManager> sm = defaultServiceManager();
1176 ASSERT_NE(nullptr, sm);
1177 // Any Java service with non-empty getInterfaceDescriptor() would do.
1178 // Let's pick batteryproperties.
1179 auto binder = sm->checkService(String16("batteryproperties"));
1180 ASSERT_NE(nullptr, binder);
1181 auto descriptor = binder->getInterfaceDescriptor();
1182 ASSERT_GE(descriptor.size(), 0);
1183 ASSERT_EQ(OK, binder->pingBinder());
1184
1185 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001186 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001187 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001188 auto socket = rpcServer->releaseServer();
1189
1190 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001191 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1192
Yifan Honge3caaf22022-01-12 14:46:56 -08001193 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1194 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001195 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001196 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1197 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001198 << statusToString(setRpcClientDebugStatus);
1199 GTEST_SKIP();
1200 }
1201
1202 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001203
1204 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001205 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001206 auto rpcBinder = rpcSession->getRootObject();
1207 ASSERT_NE(nullptr, rpcBinder);
1208
1209 ASSERT_EQ(OK, rpcBinder->pingBinder());
1210
1211 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1212 << "getInterfaceDescriptor should not crash system_server";
1213 ASSERT_EQ(OK, rpcBinder->pingBinder());
1214}
1215
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001216class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1217public:
1218 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1219 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1220 std::to_string(std::get<1>(info.param));
1221 }
1222};
1223
1224TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1225 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1226 int sinkFd = sink.get();
1227 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1228 server->setProtocolVersion(std::get<1>(GetParam()));
1229 ASSERT_FALSE(server->hasServer());
1230 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1231 ASSERT_TRUE(server->hasServer());
1232 base::unique_fd retrieved = server->releaseServer();
1233 ASSERT_FALSE(server->hasServer());
1234 ASSERT_EQ(sinkFd, retrieved.get());
1235}
1236
1237TEST_P(BinderRpcServerOnly, Shutdown) {
1238 if constexpr (!kEnableRpcThreads) {
1239 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1240 }
1241
1242 auto addr = allocateSocketAddress();
1243 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1244 server->setProtocolVersion(std::get<1>(GetParam()));
1245 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1246 auto joinEnds = std::make_shared<OneOffSignal>();
1247
1248 // If things are broken and the thread never stops, don't block other tests. Because the thread
1249 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1250 // shared pointers are passed.
1251 std::thread([server, joinEnds] {
1252 server->join();
1253 joinEnds->notify();
1254 }).detach();
1255
1256 bool shutdown = false;
1257 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001258 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001259 if (server->shutdown()) shutdown = true;
1260 }
1261 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1262
1263 ASSERT_TRUE(joinEnds->wait(2s))
1264 << "After server->shutdown() returns true, join() did not stop after 2s";
1265}
1266
Frederick Mayledc07cf82022-05-26 20:30:12 +00001267INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1268 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1269 ::testing::ValuesIn(testVersions())),
1270 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001271
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001272class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001273public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001274 // Only parameterized only server version because `RpcSession` is bypassed
1275 // in the client half of the tests.
1276 using Param =
1277 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001278 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001279
1280 // A server that handles client socket connections.
1281 class Server {
1282 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001283 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1284
Yifan Hong1deca4b2021-09-10 16:16:44 -07001285 explicit Server() {}
1286 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001287 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001288 [[nodiscard]] AssertionResult setUp(
1289 const Param& param,
1290 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001291 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001292 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001293 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001294 switch (socketType) {
1295 case SocketType::PRECONNECTED: {
1296 return AssertionFailure() << "Not supported by this test";
1297 } break;
1298 case SocketType::UNIX: {
1299 auto addr = allocateSocketAddress();
1300 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1301 if (status != OK) {
1302 return AssertionFailure()
1303 << "setupUnixDomainServer: " << statusToString(status);
1304 }
1305 mConnectToServer = [addr] {
1306 return connectTo(UnixSocketAddress(addr.c_str()));
1307 };
1308 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001309 case SocketType::UNIX_BOOTSTRAP: {
1310 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1311 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1312 return AssertionFailure() << "Socketpair() failed";
1313 }
1314 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1315 std::move(bootstrapFdServer));
1316 if (status != OK) {
1317 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1318 << statusToString(status);
1319 }
1320 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1321 mAcceptConnection = &Server::recvmsgServerConnection;
1322 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1323 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001324 case SocketType::UNIX_RAW: {
1325 auto addr = allocateSocketAddress();
1326 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1327 if (status != OK) {
1328 return AssertionFailure()
1329 << "setupRawSocketServer: " << statusToString(status);
1330 }
1331 mConnectToServer = [addr] {
1332 return connectTo(UnixSocketAddress(addr.c_str()));
1333 };
1334 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001335 case SocketType::VSOCK: {
1336 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001337 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001338 if (status != OK) {
1339 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1340 }
1341 mConnectToServer = [port] {
1342 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1343 };
1344 } break;
1345 case SocketType::INET: {
1346 unsigned int port;
1347 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1348 if (status != OK) {
1349 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1350 }
1351 mConnectToServer = [port] {
1352 const char* addr = kLocalInetAddress;
1353 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1354 if (aiStart == nullptr) return base::unique_fd{};
1355 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1356 auto fd = connectTo(
1357 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1358 if (fd.ok()) return fd;
1359 }
1360 ALOGE("None of the socket address resolved for %s:%u can be connected",
1361 addr, port);
1362 return base::unique_fd{};
1363 };
1364 }
1365 }
1366 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001367 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001368 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001369 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1370 mSetup = true;
1371 return AssertionSuccess();
1372 }
1373 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1374 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1375 return mCertVerifier;
1376 }
1377 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1378 void start() {
1379 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1380 mThread = std::make_unique<std::thread>(&Server::run, this);
1381 }
David Brazdil21c887c2022-09-23 12:25:18 +01001382
1383 base::unique_fd acceptServerConnection() {
1384 return base::unique_fd(TEMP_FAILURE_RETRY(
1385 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1386 }
1387
1388 base::unique_fd recvmsgServerConnection() {
1389 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1390 int buf;
1391 iovec iov{&buf, sizeof(buf)};
1392
1393 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1394 int savedErrno = errno;
1395 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1396 }
1397 if (fds.size() != 1) {
1398 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1399 }
1400 return std::move(std::get<base::unique_fd>(fds[0]));
1401 }
1402
Yifan Hong1deca4b2021-09-10 16:16:44 -07001403 void run() {
1404 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1405
1406 std::vector<std::thread> threads;
1407 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001408 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001409 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1410 }
1411
1412 for (auto& thread : threads) thread.join();
1413 }
1414 void handleOne(android::base::unique_fd acceptedFd) {
1415 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001416 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001417 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001418 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001419 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001420 }
Yifan Honge07d2732021-09-13 21:59:14 -07001421 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001422 shutdown();
1423 join();
1424 }
1425 void shutdown() { mFdTrigger->trigger(); }
1426
1427 void setPostConnect(
1428 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1429 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001430 }
1431
1432 private:
1433 std::unique_ptr<std::thread> mThread;
1434 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001435 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001436 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001437 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001438 std::unique_ptr<RpcTransportCtx> mCtx;
1439 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1440 std::make_shared<RpcCertificateVerifierSimple>();
1441 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001442 // The function invoked after connection and handshake. By default, it is
1443 // |defaultPostConnect| that sends |kMessage| to the client.
1444 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1445 Server::defaultPostConnect;
1446
1447 void join() {
1448 if (mThread != nullptr) {
1449 mThread->join();
1450 mThread = nullptr;
1451 }
1452 }
1453
1454 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1455 FdTrigger* fdTrigger) {
1456 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001457 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001458 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001459 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001460 if (status != OK) return AssertionFailure() << statusToString(status);
1461 return AssertionSuccess();
1462 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001463 };
1464
1465 class Client {
1466 public:
1467 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1468 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001469 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001470 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1471 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001472 mFdTrigger = FdTrigger::make();
1473 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1474 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1475 return AssertionSuccess();
1476 }
1477 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1478 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1479 return mCertVerifier;
1480 }
Yifan Hong67519322021-09-13 18:51:16 -07001481 // connect() and do handshake
1482 bool setUpTransport() {
1483 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001484 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001485 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1486 return mClientTransport != nullptr;
1487 }
1488 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1489 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1490 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001491 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001492 status_t readStatus =
1493 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001494 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001495 if (readStatus != OK) {
1496 return AssertionFailure() << statusToString(readStatus);
1497 }
1498 if (readMessage != expectedMessage) {
1499 return AssertionFailure()
1500 << "Expected " << expectedMessage << ", actual " << readMessage;
1501 }
1502 return AssertionSuccess();
1503 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001504 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001505 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001506 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1507 return;
1508 }
1509 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001510 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001511 }
1512
Pawan49d74cb2022-08-03 21:19:11 +00001513 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1514
Yifan Hong1deca4b2021-09-10 16:16:44 -07001515 private:
1516 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001517 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001518 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1519 std::unique_ptr<RpcTransportCtx> mCtx;
1520 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1521 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001522 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001523 };
1524
1525 // Make A trust B.
1526 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001527 static status_t trust(RpcSecurity rpcSecurity,
1528 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1529 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001530 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001531 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1532 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1533 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001534 }
1535
1536 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001537};
1538
1539class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1540public:
1541 using Server = RpcTransportTestUtils::Server;
1542 using Client = RpcTransportTestUtils::Client;
1543 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001544 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001545 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1546 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001547 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001548 return ret;
1549 }
1550 static std::vector<ParamType> getRpcTranportTestParams() {
1551 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001552 for (auto serverVersion : testVersions()) {
1553 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1554 for (auto rpcSecurity : RpcSecurityValues()) {
1555 switch (rpcSecurity) {
1556 case RpcSecurity::RAW: {
1557 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1558 } break;
1559 case RpcSecurity::TLS: {
1560 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1561 serverVersion);
1562 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1563 serverVersion);
1564 } break;
1565 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001566 }
1567 }
1568 }
1569 return ret;
1570 }
1571 template <typename A, typename B>
1572 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001573 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1574 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001575 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1576 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001577 void SetUp() override {
1578 if constexpr (!kEnableRpcThreads) {
1579 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1580 }
1581 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001582};
1583
1584TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001585 auto server = std::make_unique<Server>();
1586 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001587
1588 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001589 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001590
1591 ASSERT_EQ(OK, trust(&client, server));
1592 ASSERT_EQ(OK, trust(server, &client));
1593
1594 server->start();
1595 client.run();
1596}
1597
1598TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001599 auto server = std::make_unique<Server>();
1600 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001601
1602 std::vector<Client> clients;
1603 for (int i = 0; i < 2; i++) {
1604 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001605 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001606 ASSERT_EQ(OK, trust(&client, server));
1607 ASSERT_EQ(OK, trust(server, &client));
1608 }
1609
1610 server->start();
1611 for (auto& client : clients) client.run();
1612}
1613
1614TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001615 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1616 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001617
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001618 auto untrustedServer = std::make_unique<Server>();
1619 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620
1621 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001622 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623
1624 ASSERT_EQ(OK, trust(untrustedServer, &client));
1625
1626 untrustedServer->start();
1627
1628 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1629 // the client can't verify the server's identity.
1630 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1631 client.run(handshakeOk);
1632}
1633TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001634 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1635 (void)serverVersion;
1636
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001637 auto validServer = std::make_unique<Server>();
1638 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001639
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001640 auto maliciousServer = std::make_unique<Server>();
1641 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642
1643 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001644 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001645
1646 ASSERT_EQ(OK, trust(&client, validServer));
1647 ASSERT_EQ(OK, trust(validServer, &client));
1648 ASSERT_EQ(OK, trust(maliciousServer, &client));
1649
1650 maliciousServer->start();
1651
1652 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1653 // the client can't verify the server's identity.
1654 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1655 client.run(handshakeOk);
1656}
1657
1658TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001659 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1660 (void)serverVersion;
1661
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001662 auto server = std::make_unique<Server>();
1663 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001664
1665 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001666 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001667
1668 ASSERT_EQ(OK, trust(&client, server));
1669
1670 server->start();
1671
1672 // For TLS, Client should be able to verify server's identity, so client should see
1673 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1674 // identity and should drop the connection, so client shouldn't be able to read anything.
1675 bool readOk = rpcSecurity != RpcSecurity::TLS;
1676 client.run(true, readOk);
1677}
1678
1679TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001680 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1681 (void)serverVersion;
1682
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001683 auto server = std::make_unique<Server>();
1684 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001685
1686 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001687 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001688 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001689 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001690
1691 ASSERT_EQ(OK, trust(&validClient, server));
1692 ASSERT_EQ(OK, trust(&maliciousClient, server));
1693
1694 server->start();
1695
1696 // See UntrustedClient.
1697 bool readOk = rpcSecurity != RpcSecurity::TLS;
1698 maliciousClient.run(true, readOk);
1699}
1700
Yifan Hong67519322021-09-13 18:51:16 -07001701TEST_P(RpcTransportTest, Trigger) {
1702 std::string msg2 = ", world!";
1703 std::mutex writeMutex;
1704 std::condition_variable writeCv;
1705 bool shouldContinueWriting = false;
1706 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001707 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001708 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001709 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1710 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001711 if (status != OK) return AssertionFailure() << statusToString(status);
1712
1713 {
1714 std::unique_lock<std::mutex> lock(writeMutex);
1715 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1716 return AssertionFailure() << "write barrier not cleared in time!";
1717 }
1718 }
1719
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001720 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001721 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1722 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001723 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001724 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001725 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001726 << statusToString(status);
1727 return AssertionSuccess();
1728 };
1729
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001730 auto server = std::make_unique<Server>();
1731 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001732
1733 // Set up client
1734 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001735 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001736
1737 // Exchange keys
1738 ASSERT_EQ(OK, trust(&client, server));
1739 ASSERT_EQ(OK, trust(server, &client));
1740
1741 server->setPostConnect(serverPostConnect);
1742
Yifan Hong67519322021-09-13 18:51:16 -07001743 server->start();
1744 // connect() to server and do handshake
1745 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001746 // read the first message. This ensures that server has finished handshake and start handling
1747 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001748 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001749 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1750 // write is on an FdTrigger that has been shut down.
1751 server->shutdown();
1752 // Continues server thread to write the second message.
1753 {
Yifan Hong22211f82021-09-14 12:32:25 -07001754 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001755 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001756 }
Yifan Hong22211f82021-09-14 12:32:25 -07001757 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001758 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001759 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001760 // On the client side, second read fails with DEAD_OBJECT
1761 ASSERT_FALSE(client.readMessage(msg2));
1762}
1763
Pawan49d74cb2022-08-03 21:19:11 +00001764TEST_P(RpcTransportTest, CheckWaitingForRead) {
1765 std::mutex readMutex;
1766 std::condition_variable readCv;
1767 bool shouldContinueReading = false;
1768 // Server will write data on transport once its started
1769 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1770 std::string message(RpcTransportTestUtils::kMessage);
1771 iovec messageIov{message.data(), message.size()};
1772 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1773 std::nullopt, nullptr);
1774 if (status != OK) return AssertionFailure() << statusToString(status);
1775
1776 {
1777 std::unique_lock<std::mutex> lock(readMutex);
1778 shouldContinueReading = true;
1779 lock.unlock();
1780 readCv.notify_all();
1781 }
1782 return AssertionSuccess();
1783 };
1784
1785 // Setup Server and client
1786 auto server = std::make_unique<Server>();
1787 ASSERT_TRUE(server->setUp(GetParam()));
1788
1789 Client client(server->getConnectToServerFn());
1790 ASSERT_TRUE(client.setUp(GetParam()));
1791
1792 ASSERT_EQ(OK, trust(&client, server));
1793 ASSERT_EQ(OK, trust(server, &client));
1794 server->setPostConnect(serverPostConnect);
1795
1796 server->start();
1797 ASSERT_TRUE(client.setUpTransport());
1798 {
1799 // Wait till server writes data
1800 std::unique_lock<std::mutex> lock(readMutex);
1801 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1802 }
1803
1804 // Since there is no read polling here, we will get polling count 0
1805 ASSERT_FALSE(client.isTransportWaiting());
1806 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1807 // Thread should increment polling count, read and decrement polling count
1808 // Again, polling count should be zero here
1809 ASSERT_FALSE(client.isTransportWaiting());
1810
1811 server->shutdown();
1812}
1813
Yifan Hong1deca4b2021-09-10 16:16:44 -07001814INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001815 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001816 RpcTransportTest::PrintParamInfo);
1817
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001818class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001819 : public testing::TestWithParam<
1820 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001821public:
1822 template <typename A, typename B>
1823 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001824 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1825 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001826 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1827 }
1828 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001829 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1830 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1831 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001832 };
1833};
1834
1835TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001836 if constexpr (!kEnableRpcThreads) {
1837 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1838 }
1839
Frederick Mayledc07cf82022-05-26 20:30:12 +00001840 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001841
1842 std::vector<uint8_t> pkeyData, certData;
1843 {
1844 auto pkey = makeKeyPairForSelfSignedCert();
1845 ASSERT_NE(nullptr, pkey);
1846 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1847 ASSERT_NE(nullptr, cert);
1848 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1849 certData = serializeCertificate(cert.get(), certificateFormat);
1850 }
1851
1852 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1853 auto desCert = deserializeCertificate(certData, certificateFormat);
1854 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001855 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1856 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001857
1858 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1859 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1860
1861 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1862 ASSERT_TRUE(client.setUp(utilsParam));
1863
1864 ASSERT_EQ(OK, trust(&client, server));
1865 ASSERT_EQ(OK, trust(server, &client));
1866
1867 server->start();
1868 client.run();
1869}
1870
1871INSTANTIATE_TEST_CASE_P(
1872 BinderRpc, RpcTransportTlsKeyTest,
1873 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1874 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001875 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1876 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001877 RpcTransportTlsKeyTest::PrintParamInfo);
1878
Steven Morelandc1635952021-04-01 16:20:47 +00001879} // namespace android
1880
1881int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001882 ::testing::InitGoogleTest(&argc, argv);
1883 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001884
Steven Moreland5553ac42020-11-11 02:14:45 +00001885 return RUN_ALL_TESTS();
1886}