blob: f0400d3c0dea820418eca56abaae935823a67938 [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
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000017#ifndef __ANDROID_VENDOR__
18// only used on NDK tests outside of vendor
Andrei Homescu9d8adb12022-08-02 04:38:30 +000019#include <aidl/IBinderRpcTest.h>
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000020#endif
Steven Moreland5553ac42020-11-11 02:14:45 +000021
Steven Morelandc1635952021-04-01 16:20:47 +000022#include <chrono>
23#include <cstdlib>
24#include <iostream>
25#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000026#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000027
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070028#include <dirent.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000029#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070030#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000031#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000032#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000033
Andrei Homescud65666d2023-03-03 07:28:02 +000034#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000035#include <binder/RpcTransportTipcAndroid.h>
36#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000037#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000038
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -080039#include "../Utils.h"
Andrei Homescu2a298012022-06-15 01:08:54 +000040#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000041#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000042
Yifan Hong1a235852021-05-13 16:07:47 -070043using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070044using namespace std::placeholders;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070045using android::binder::borrowed_fd;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -070046using android::binder::GetExecutableDirectory;
47using android::binder::ReadFdToString;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070048using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070049using testing::AssertionFailure;
50using testing::AssertionResult;
51using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070052
Steven Moreland5553ac42020-11-11 02:14:45 +000053namespace android {
54
Andrei Homescu12106de2022-04-27 04:42:21 +000055#ifdef BINDER_TEST_NO_SHARED_LIBS
56constexpr bool kEnableSharedLibs = false;
57#else
58constexpr bool kEnableSharedLibs = true;
59#endif
60
Andrei Homescud65666d2023-03-03 07:28:02 +000061#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000062constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
63#endif
64
Frederick Maylea12b0962022-06-25 01:13:22 +000065static std::string WaitStatusToString(int wstatus) {
66 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000067 return std::format("exit status {}", WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000068 }
69 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000070 return std::format("term signal {}", WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000071 }
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000072 return std::format("unexpected state {}", wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000073}
74
Steven Moreland276d8df2022-09-28 23:56:39 +000075static void debugBacktrace(pid_t pid) {
76 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
77 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
78}
79
Steven Moreland5553ac42020-11-11 02:14:45 +000080class Process {
81public:
Andrei Homescu96834632022-10-14 00:49:49 +000082 Process(Process&& other)
83 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
84 mReadEnd(std::move(other.mReadEnd)),
85 mWriteEnd(std::move(other.mWriteEnd)) {
86 // The default move constructor doesn't clear mPid after moving it,
87 // which we need to do because the destructor checks for mPid!=0
88 mPid = other.mPid;
89 other.mPid = 0;
90 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070091 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
92 unique_fd childWriteEnd;
93 unique_fd childReadEnd;
94 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
95 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +000096 if (0 == (mPid = fork())) {
97 // racey: assume parent doesn't crash before this is set
98 prctl(PR_SET_PDEATHSIG, SIGHUP);
99
Yifan Hong1deca4b2021-09-10 16:16:44 -0700100 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000101
102 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000103 }
104 }
105 ~Process() {
106 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000107 int wstatus;
108 waitpid(mPid, &wstatus, 0);
109 if (mCustomExitStatusCheck) {
110 mCustomExitStatusCheck(wstatus);
111 } else {
112 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
113 << "server process failed: " << WaitStatusToString(wstatus);
114 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000115 }
116 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700117 borrowed_fd readEnd() { return mReadEnd; }
118 borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000119
Frederick Maylea12b0962022-06-25 01:13:22 +0000120 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
121 mCustomExitStatusCheck = std::move(f);
122 }
123
Frederick Mayle69a0c992022-05-26 20:38:39 +0000124 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
125 void terminate() { kill(mPid, SIGTERM); }
126
Steven Moreland276d8df2022-09-28 23:56:39 +0000127 pid_t getPid() { return mPid; }
128
Steven Moreland5553ac42020-11-11 02:14:45 +0000129private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000130 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000131 pid_t mPid = 0;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700132 unique_fd mReadEnd;
133 unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000134};
135
136static std::string allocateSocketAddress() {
137 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000138 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000139 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700140 unlink(ret.c_str());
141 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000142};
143
Steven Morelandda573042021-06-12 01:13:45 +0000144static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000145 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000146 return vsockPort++;
147}
148
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700149static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000150 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700151 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700152 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
153 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
154 PLOGF("initUnixSocket failed to bind");
155 }
Alice Wang893a9912022-10-24 10:44:09 +0000156 return fd;
157}
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159// Destructors need to be defined, even if pure virtual
160ProcessSession::~ProcessSession() {}
161
162class LinuxProcessSession : public ProcessSession {
163public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000164 // reference to process hosting a socket server
165 Process host;
166
Andrei Homescu96834632022-10-14 00:49:49 +0000167 LinuxProcessSession(LinuxProcessSession&&) = default;
168 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
169 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 for (auto& session : sessions) {
171 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000172 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
Steven Moreland67f85902023-03-15 01:13:49 +0000174 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
175 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000176 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 EXPECT_NE(nullptr, session);
179 EXPECT_NE(nullptr, session->state());
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700180 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000181
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000182 wp<RpcSession> weakSession = session;
183 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000184
Steven Moreland57042712022-10-04 23:56:45 +0000185 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
186 // the object should not actually be promotable. By looping, we distinguish a race here
187 // from a bug causing the object to not be promotable.
188 for (size_t i = 0; i < 3; i++) {
189 sp<RpcSession> strongSession = weakSession.promote();
190 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000191 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000192 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
193 "Leaked sess: ")
194 << strongSession->getStrongCount() << " checked time " << i;
195
196 if (strongSession != nullptr) {
197 sleep(1);
198 }
199 }
Steven Moreland736664b2021-05-01 04:27:25 +0000200 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000201 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000202
Andrei Homescu96834632022-10-14 00:49:49 +0000203 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
204 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000205 }
Andrei Homescu96834632022-10-14 00:49:49 +0000206
207 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000208};
209
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700210static unique_fd connectTo(const RpcSocketAddress& addr) {
211 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700212 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700213 if (!serverFd.ok()) {
214 PLOGF("Could not create socket %s", addr.toString().c_str());
215 }
Steven Moreland4198a122021-08-03 17:37:58 -0700216
217 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700218 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700219 }
220 return serverFd;
221}
222
Andrei Homescud65666d2023-03-03 07:28:02 +0000223#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700224static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
225 unique_fd sockClient, sockServer;
226 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700227 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100228 }
229
230 int zero = 0;
231 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700232 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100233 fds.emplace_back(std::move(sockServer));
234
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000235 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700236 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100237 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700238 return sockClient;
David Brazdil21c887c2022-09-23 12:25:18 +0100239}
Andrei Homescud65666d2023-03-03 07:28:02 +0000240#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100241
Andrei Homescuf30148c2023-03-10 00:31:45 +0000242std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
243 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000244}
Andrei Homescu2a298012022-06-15 01:08:54 +0000245
Andrei Homescu96834632022-10-14 00:49:49 +0000246// This creates a new process serving an interface on a certain number of
247// threads.
248std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
249 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700250 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000251
Steven Moreland67f85902023-03-15 01:13:49 +0000252 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700253 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
254 "%s: %zu != %zu", __func__,
255 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000256 }
257
Steven Morelandb469f432023-07-28 22:13:47 +0000258 SocketType socketType = GetParam().type;
259 RpcSecurity rpcSecurity = GetParam().security;
260 uint32_t clientVersion = GetParam().clientVersion;
261 uint32_t serverVersion = GetParam().serverVersion;
262 bool singleThreaded = GetParam().singleThreaded;
263 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000264
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700265 std::string path = GetExecutableDirectory();
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000266 auto servicePath =
267 std::format("{}/binder_rpc_test_service{}{}", path,
268 singleThreaded ? "_single_threaded" : "", noKernel ? "_no_kernel" : "");
Andrei Homescu96834632022-10-14 00:49:49 +0000269
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700270 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000271
Alice Wang893a9912022-10-24 10:44:09 +0000272 auto addr = allocateSocketAddress();
273 // Initializes the socket before the fork/exec.
274 if (socketType == SocketType::UNIX_RAW) {
275 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000276 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
277 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
278 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700279 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700280 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000281 }
Alice Wang893a9912022-10-24 10:44:09 +0000282 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000283
Andrei Homescu96834632022-10-14 00:49:49 +0000284 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700285 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000286 if (socketType == SocketType::TIPC) {
287 // Trusty has a single persistent service
288 return;
289 }
290
Andrei Homescu96834632022-10-14 00:49:49 +0000291 auto writeFd = std::to_string(writeEnd.get());
292 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800293 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
294 readFd.c_str(), NULL);
295 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
296 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000297 }));
298
299 BinderRpcTestServerConfig serverConfig;
300 serverConfig.numThreads = options.numThreads;
301 serverConfig.socketType = static_cast<int32_t>(socketType);
302 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
303 serverConfig.serverVersion = serverVersion;
304 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000305 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000306 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000307 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
308 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
309 static_cast<int32_t>(mode));
310 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 if (socketType != SocketType::TIPC) {
312 writeToFd(ret->host.writeEnd(), serverConfig);
313 }
Andrei Homescu96834632022-10-14 00:49:49 +0000314
315 std::vector<sp<RpcSession>> sessions;
316 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
317 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000318 std::unique_ptr<RpcTransportCtxFactory> factory;
319 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000320#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000321 factory = RpcTransportCtxFactoryTipcAndroid::make();
322#else
323 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
324#endif
325 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000326 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000327 }
328 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100329 }
330
Andrei Homescu68a55612022-08-02 01:25:15 +0000331 BinderRpcTestServerInfo serverInfo;
332 if (socketType != SocketType::TIPC) {
333 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
334 BinderRpcTestClientInfo clientInfo;
335 for (const auto& session : sessions) {
336 auto& parcelableCert = clientInfo.certs.emplace_back();
337 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
338 }
339 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000340
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700341 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000342 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700343 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000344 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000345
Andrei Homescu68a55612022-08-02 01:25:15 +0000346 if (rpcSecurity == RpcSecurity::TLS) {
347 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700348 LOG_ALWAYS_FATAL_IF(
349 OK !=
350 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000351 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 }
353
Andrei Homescu96834632022-10-14 00:49:49 +0000354 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000355
Steven Moreland67f85902023-03-15 01:13:49 +0000356 for (size_t i = 0; i < sessions.size(); i++) {
357 const auto& session = sessions.at(i);
358
359 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
360 ? options.numIncomingConnectionsBySession.at(i)
361 : 0;
362
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700363 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000364 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000365 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000366 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000367
Andrei Homescu96834632022-10-14 00:49:49 +0000368 switch (socketType) {
369 case SocketType::PRECONNECTED:
370 status = session->setupPreconnectedClient({}, [=]() {
371 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
372 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000373 break;
Alice Wang893a9912022-10-24 10:44:09 +0000374 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000375 case SocketType::UNIX:
376 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
377 break;
378 case SocketType::UNIX_BOOTSTRAP:
379 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700380 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000381 break;
382 case SocketType::VSOCK:
383 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
384 break;
385 case SocketType::INET:
386 status = session->setupInetClient("127.0.0.1", serverInfo.port);
387 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000388 case SocketType::TIPC:
389 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000390#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000391 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000392 for (size_t i = 0; i < 5; i++) {
393 // Try to connect several times,
394 // in case the service is slow to start
395 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
396 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700397 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000398 }
399 usleep(50000);
400 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700401 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000402#else
403 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700404 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000405#endif
406 });
407 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000408 default:
409 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000410 }
Andrei Homescu96834632022-10-14 00:49:49 +0000411 if (options.allowConnectFailure && status != OK) {
412 ret->sessions.clear();
413 break;
414 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700415 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Andrei Homescu96834632022-10-14 00:49:49 +0000416 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000417 }
Andrei Homescu96834632022-10-14 00:49:49 +0000418 return ret;
419}
Steven Morelandc1635952021-04-01 16:20:47 +0000420
Andrei Homescua858b0e2022-08-01 23:43:09 +0000421TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
422 if (clientOrServerSingleThreaded()) {
423 GTEST_SKIP() << "This test requires multiple threads";
424 }
425
Steven Moreland5553ac42020-11-11 02:14:45 +0000426 constexpr size_t kNumThreads = 10;
427
Steven Moreland4313d7e2021-07-15 23:41:22 +0000428 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000429
430 EXPECT_OK(proc.rootIface->lock());
431
432 // block all but one thread taking locks
433 std::vector<std::thread> ts;
434 for (size_t i = 0; i < kNumThreads - 1; i++) {
435 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
436 }
437
Steven Morelandd6d816f2022-12-23 01:37:17 +0000438 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000439
440 // other calls still work
441 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
442
Steven Morelandd6d816f2022-12-23 01:37:17 +0000443 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000444 size_t epochMsBefore = epochMillis();
445 // after this, we should never see a response within this time
446 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
447
448 // this call should be blocked for blockTimeMs
449 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
450
451 size_t epochMsAfter = epochMillis();
452 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
453
454 for (auto& t : ts) t.join();
455}
456
Steven Moreland27f620a2023-03-06 19:44:36 +0000457static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000458 size_t epochMsBefore = epochMillis();
459
460 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700461 for (size_t i = 0; i < numCalls; i++) {
462 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000463 }
464
465 for (auto& t : ts) t.join();
466
467 size_t epochMsAfter = epochMillis();
468
Yifan Hong1f44f982021-10-08 17:16:47 -0700469 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000470
Steven Moreland9c203222023-05-31 21:26:41 +0000471 // Potential flake, but make sure calls are handled in parallel. Due
472 // to past flakes, this only checks that the amount of time taken has
473 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
474 // check this more exactly.
475 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700476}
477
Andrei Homescua858b0e2022-08-01 23:43:09 +0000478TEST_P(BinderRpc, ThreadPoolOverSaturated) {
479 if (clientOrServerSingleThreaded()) {
480 GTEST_SKIP() << "This test requires multiple threads";
481 }
482
Yifan Hong1f44f982021-10-08 17:16:47 -0700483 constexpr size_t kNumThreads = 10;
484 constexpr size_t kNumCalls = kNumThreads + 3;
485 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000486
487 // b/272429574 - below 500ms, the test fails
488 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700489}
490
Andrei Homescua858b0e2022-08-01 23:43:09 +0000491TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
492 if (clientOrServerSingleThreaded()) {
493 GTEST_SKIP() << "This test requires multiple threads";
494 }
495
Yifan Hong1f44f982021-10-08 17:16:47 -0700496 constexpr size_t kNumThreads = 20;
497 constexpr size_t kNumOutgoingConnections = 10;
498 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
499 auto proc = createRpcTestSocketServerProcess(
500 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000501
502 // b/272429574 - below 500ms, the test fails
503 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000504}
505
Andrei Homescua858b0e2022-08-01 23:43:09 +0000506TEST_P(BinderRpc, ThreadingStressTest) {
507 if (clientOrServerSingleThreaded()) {
508 GTEST_SKIP() << "This test requires multiple threads";
509 }
510
Steven Moreland27f620a2023-03-06 19:44:36 +0000511 constexpr size_t kNumClientThreads = 5;
512 constexpr size_t kNumServerThreads = 5;
513 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000514
Steven Moreland4313d7e2021-07-15 23:41:22 +0000515 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000516
517 std::vector<std::thread> threads;
518 for (size_t i = 0; i < kNumClientThreads; i++) {
519 threads.push_back(std::thread([&] {
520 for (size_t j = 0; j < kNumCalls; j++) {
521 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000522 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000523 EXPECT_EQ(proc.rootBinder, out);
524 }
525 }));
526 }
527
528 for (auto& t : threads) t.join();
529}
530
Steven Moreland925ba0a2021-09-17 18:06:32 -0700531static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
532 std::vector<std::thread> threads;
533 for (size_t i = 0; i < threadCount; i++) {
534 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
535 }
536 for (auto& t : threads) t.join();
537}
538
Andrei Homescua858b0e2022-08-01 23:43:09 +0000539TEST_P(BinderRpc, OnewayStressTest) {
540 if (clientOrServerSingleThreaded()) {
541 GTEST_SKIP() << "This test requires multiple threads";
542 }
543
Steven Morelandc6046982021-04-20 00:49:42 +0000544 constexpr size_t kNumClientThreads = 10;
545 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700546 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000547
Steven Moreland4313d7e2021-07-15 23:41:22 +0000548 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000549
550 std::vector<std::thread> threads;
551 for (size_t i = 0; i < kNumClientThreads; i++) {
552 threads.push_back(std::thread([&] {
553 for (size_t j = 0; j < kNumCalls; j++) {
554 EXPECT_OK(proc.rootIface->sendString("a"));
555 }
Steven Morelandc6046982021-04-20 00:49:42 +0000556 }));
557 }
558
559 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700560
561 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000562}
563
Frederick Mayleb0221d12022-10-03 23:10:53 +0000564TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
565 if (!supportsFdTransport()) {
566 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
567 }
568 if (clientOrServerSingleThreaded()) {
569 GTEST_SKIP() << "This test requires multiple threads";
570 }
571
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000572 constexpr size_t kNumServerThreads = 3;
573
Frederick Mayleb0221d12022-10-03 23:10:53 +0000574 // This test forces a oneway transaction to be queued by issuing two
575 // `blockingSendFdOneway` calls, then drains the queue by issuing two
576 // `blockingRecvFd` calls.
577 //
578 // For more details about the queuing semantics see
579 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
580
581 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000582 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000583 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
584 .serverSupportedFileDescriptorTransportModes =
585 {RpcSession::FileDescriptorTransportMode::UNIX},
586 });
587
588 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
589 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
590 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
591 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
592
593 android::os::ParcelFileDescriptor fdA;
594 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
595 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700596 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000597 EXPECT_EQ(result, "a");
598
599 android::os::ParcelFileDescriptor fdB;
600 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700601 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000602 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000603
604 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000605}
606
Andrei Homescua858b0e2022-08-01 23:43:09 +0000607TEST_P(BinderRpc, OnewayCallQueueing) {
608 if (clientOrServerSingleThreaded()) {
609 GTEST_SKIP() << "This test requires multiple threads";
610 }
611
Frederick Mayle96872592023-03-07 14:56:15 -0800612 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000614
615 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000616 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000617
Frederick Mayle96872592023-03-07 14:56:15 -0800618 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700619 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800620 for (size_t i = 0; i + 1 < kNumQueued; i++) {
621 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 }
Frederick Mayle96872592023-03-07 14:56:15 -0800623 for (size_t i = 0; i + 1 < kNumQueued; i++) {
624 int n;
625 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700626 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800627 }
Steven Morelandf5174272021-05-25 00:39:28 +0000628
Steven Moreland925ba0a2021-09-17 18:06:32 -0700629 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000630}
631
Andrei Homescua858b0e2022-08-01 23:43:09 +0000632TEST_P(BinderRpc, OnewayCallExhaustion) {
633 if (clientOrServerSingleThreaded()) {
634 GTEST_SKIP() << "This test requires multiple threads";
635 }
636
Steven Morelandd45be622021-06-04 02:19:37 +0000637 constexpr size_t kNumClients = 2;
638 constexpr size_t kTooLongMs = 1000;
639
Steven Moreland4313d7e2021-07-15 23:41:22 +0000640 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000641
642 // Build up oneway calls on the second session to make sure it terminates
643 // and shuts down. The first session should be unaffected (proc destructor
644 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000645 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000646
647 std::vector<std::thread> threads;
648 for (size_t i = 0; i < kNumClients; i++) {
649 // one of these threads will get stuck queueing a transaction once the
650 // socket fills up, the other will be able to fill up transactions on
651 // this object
652 threads.push_back(std::thread([&] {
653 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
654 }
655 }));
656 }
657 for (auto& t : threads) t.join();
658
659 Status status = iface->sleepMsAsync(kTooLongMs);
660 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
661
Steven Moreland798e0d12021-07-14 23:19:25 +0000662 // now that it has died, wait for the remote session to shutdown
663 std::vector<int32_t> remoteCounts;
664 do {
665 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
666 } while (remoteCounts.size() == kNumClients);
667
Steven Morelandd45be622021-06-04 02:19:37 +0000668 // the second session should be shutdown in the other process by the time we
669 // are able to join above (it'll only be hung up once it finishes processing
670 // any pending commands). We need to erase this session from the record
671 // here, so that the destructor for our session won't check that this
672 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000673 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000674}
675
Steven Moreland67f85902023-03-15 01:13:49 +0000676TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
677 if (clientOrServerSingleThreaded()) {
678 GTEST_SKIP() << "This test requires multiple threads";
679 }
680
681 // session 0 - will check for leaks in destrutor of proc
682 // session 1 - we want to make sure it gets deleted when we drop all references to it
683 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700684 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000685
686 wp<RpcSession> session = proc.proc->sessions.at(1).session;
687
688 // remove all references to the second session
689 proc.proc->sessions.at(1).root = nullptr;
690 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
691
692 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
693 // to drain commands.
694 for (size_t i = 0; i < 100; i++) {
695 usleep(10 * 1000);
696 if (session.promote() == nullptr) break;
697 }
698
699 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000700
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000701 // now that it has died, wait for the remote session to shutdown
702 std::vector<int32_t> remoteCounts;
703 do {
704 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
705 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000706}
707
Devin Moore66d5b7a2022-07-07 21:42:10 +0000708TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000709 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000710 GTEST_SKIP() << "This test requires multiple threads";
711 }
712 class MyDeathRec : public IBinder::DeathRecipient {
713 public:
714 void binderDied(const wp<IBinder>& /* who */) override {
715 dead = true;
716 mCv.notify_one();
717 }
718 std::mutex mMtx;
719 std::condition_variable mCv;
720 bool dead = false;
721 };
722
723 // Death recipient needs to have an incoming connection to be called
724 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000725 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000726
727 auto dr = sp<MyDeathRec>::make();
728 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
729
730 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
731 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
732 }
733
734 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000735 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000736
737 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000738 // can't do this before checking the death recipient by calling
739 // forceShutdown earlier, because shutdownAndWait will also trigger
740 // a death recipient, but if we had a way to wait for the service
741 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000742 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000743 proc.expectAlreadyShutdown = true;
744}
745
746TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000747 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000748 GTEST_SKIP() << "This test requires multiple threads";
749 }
750 class MyDeathRec : public IBinder::DeathRecipient {
751 public:
752 void binderDied(const wp<IBinder>& /* who */) override {
753 dead = true;
754 mCv.notify_one();
755 }
756 std::mutex mMtx;
757 std::condition_variable mCv;
758 bool dead = false;
759 };
760
761 // Death recipient needs to have an incoming connection to be called
762 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000763 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000764
765 auto dr = sp<MyDeathRec>::make();
766 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
767
768 // Explicitly calling shutDownAndWait will cause the death recipients
769 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000770 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000771
772 std::unique_lock<std::mutex> lock(dr->mMtx);
773 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000774 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000775 }
776 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
777
Andrei Homescu96834632022-10-14 00:49:49 +0000778 proc.proc->terminate();
779 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000780 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
781 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
782 });
783 proc.expectAlreadyShutdown = true;
784}
785
Steven Moreland5ec743f2023-01-18 01:02:06 +0000786TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000787 if (socketType() == SocketType::TIPC) {
788 // This should work, but Trusty takes too long to restart the service
789 GTEST_SKIP() << "Service death test not supported on Trusty";
790 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000791 class MyDeathRec : public IBinder::DeathRecipient {
792 public:
793 void binderDied(const wp<IBinder>& /* who */) override {}
794 };
795
Steven Moreland67f85902023-03-15 01:13:49 +0000796 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000797
798 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000799 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000800}
801
802TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000803 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000804 GTEST_SKIP() << "This test requires multiple threads";
805 }
806 class MyDeathRec : public IBinder::DeathRecipient {
807 public:
808 void binderDied(const wp<IBinder>& /* who */) override {
809 GTEST_FAIL() << "This should not be called after unlinkToDeath";
810 }
811 };
812
813 // Death recipient needs to have an incoming connection to be called
814 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000815 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000816
817 auto dr = sp<MyDeathRec>::make();
818 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
819 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
820
Steven Moreland67f85902023-03-15 01:13:49 +0000821 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000822}
823
Steven Morelandc1635952021-04-01 16:20:47 +0000824TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000825 if (socketType() == SocketType::TIPC) {
826 // This should work, but Trusty takes too long to restart the service
827 GTEST_SKIP() << "Service death test not supported on Trusty";
828 }
829
Steven Moreland5553ac42020-11-11 02:14:45 +0000830 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000831 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000832
833 // make sure there is some state during crash
834 // 1. we hold their binder
835 sp<IBinderRpcSession> session;
836 EXPECT_OK(proc.rootIface->openSession("happy", &session));
837 // 2. they hold our binder
838 sp<IBinder> binder = new BBinder();
839 EXPECT_OK(proc.rootIface->holdBinder(binder));
840
841 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
842 << "Do death cleanup: " << doDeathCleanup;
843
Andrei Homescu96834632022-10-14 00:49:49 +0000844 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000845 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
846 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
847 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000848 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000849 }
850}
851
Steven Morelandd7302072021-05-15 01:32:04 +0000852TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000853 // This test only works if the current process shared the internal state of
854 // ProcessState with the service across the call to fork(). Both the static
855 // libraries and libbinder.so have their own separate copies of all the
856 // globals, so the test only works when the test client and service both use
857 // libbinder.so (when using static libraries, even a client and service
858 // using the same kind of static library should have separate copies of the
859 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000860 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000861 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
862 "at build time.";
863 }
864
Steven Moreland4313d7e2021-07-15 23:41:22 +0000865 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000866
Andrei Homescu2a298012022-06-15 01:08:54 +0000867 // we can't allocate IPCThreadState so actually the first time should
868 // succeed :(
869 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000870
871 // second time! we catch the error :)
872 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
873
Andrei Homescu96834632022-10-14 00:49:49 +0000874 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000875 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
876 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
877 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000878 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000879}
880
Frederick Mayle69a0c992022-05-26 20:38:39 +0000881TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000882 if (socketType() == SocketType::TIPC) {
883 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
884 }
885
Frederick Mayle69a0c992022-05-26 20:38:39 +0000886 auto proc = createRpcTestSocketServerProcess({
887 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
888 .serverSupportedFileDescriptorTransportModes =
889 {RpcSession::FileDescriptorTransportMode::UNIX},
890 .allowConnectFailure = true,
891 });
Andrei Homescu96834632022-10-14 00:49:49 +0000892 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
893 proc.proc->terminate();
894 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000895 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
896 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
897 });
898 proc.expectAlreadyShutdown = true;
899}
900
901TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000902 if (socketType() == SocketType::TIPC) {
903 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
904 }
905
Frederick Mayle69a0c992022-05-26 20:38:39 +0000906 auto proc = createRpcTestSocketServerProcess({
907 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
908 .serverSupportedFileDescriptorTransportModes =
909 {RpcSession::FileDescriptorTransportMode::NONE},
910 .allowConnectFailure = true,
911 });
Andrei Homescu96834632022-10-14 00:49:49 +0000912 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
913 proc.proc->terminate();
914 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000915 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
916 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
917 });
918 proc.expectAlreadyShutdown = true;
919}
920
921TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000922 if (socketType() == SocketType::TIPC) {
923 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
924 }
925
Frederick Mayle69a0c992022-05-26 20:38:39 +0000926 auto proc = createRpcTestSocketServerProcess({
927 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
928 .serverSupportedFileDescriptorTransportModes =
929 {RpcSession::FileDescriptorTransportMode::NONE,
930 RpcSession::FileDescriptorTransportMode::UNIX},
931 });
932
933 android::os::ParcelFileDescriptor out;
934 auto status = proc.rootIface->echoAsFile("hello", &out);
935 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
936}
937
938TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000939 if (socketType() == SocketType::TIPC) {
940 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
941 }
942
Frederick Mayle69a0c992022-05-26 20:38:39 +0000943 auto proc = createRpcTestSocketServerProcess({
944 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
945 .serverSupportedFileDescriptorTransportModes =
946 {RpcSession::FileDescriptorTransportMode::UNIX},
947 });
948
949 android::os::ParcelFileDescriptor out;
950 auto status = proc.rootIface->echoAsFile("hello", &out);
951 if (!supportsFdTransport()) {
952 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
953 return;
954 }
955 ASSERT_TRUE(status.isOk()) << status;
956
957 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700958 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700959 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000960}
961
962TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000963 if (socketType() == SocketType::TIPC) {
964 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
965 }
966
Frederick Mayle69a0c992022-05-26 20:38:39 +0000967 auto proc = createRpcTestSocketServerProcess({
968 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
969 .serverSupportedFileDescriptorTransportModes =
970 {RpcSession::FileDescriptorTransportMode::UNIX},
971 });
972
973 std::vector<android::os::ParcelFileDescriptor> files;
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
975 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
976 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
977 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
978
979 android::os::ParcelFileDescriptor out;
980 auto status = proc.rootIface->concatFiles(files, &out);
981 if (!supportsFdTransport()) {
982 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
983 return;
984 }
985 ASSERT_TRUE(status.isOk()) << status;
986
987 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700988 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000989 EXPECT_EQ(result, "123abcd");
990}
991
992TEST_P(BinderRpc, SendMaxFiles) {
993 if (!supportsFdTransport()) {
994 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
995 }
996
997 auto proc = createRpcTestSocketServerProcess({
998 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
999 .serverSupportedFileDescriptorTransportModes =
1000 {RpcSession::FileDescriptorTransportMode::UNIX},
1001 });
1002
1003 std::vector<android::os::ParcelFileDescriptor> files;
1004 for (int i = 0; i < 253; i++) {
1005 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1006 }
1007
1008 android::os::ParcelFileDescriptor out;
1009 auto status = proc.rootIface->concatFiles(files, &out);
1010 ASSERT_TRUE(status.isOk()) << status;
1011
1012 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001013 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001014 EXPECT_EQ(result, std::string(253, 'a'));
1015}
1016
1017TEST_P(BinderRpc, SendTooManyFiles) {
1018 if (!supportsFdTransport()) {
1019 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1020 }
1021
1022 auto proc = createRpcTestSocketServerProcess({
1023 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1024 .serverSupportedFileDescriptorTransportModes =
1025 {RpcSession::FileDescriptorTransportMode::UNIX},
1026 });
1027
1028 std::vector<android::os::ParcelFileDescriptor> files;
1029 for (int i = 0; i < 254; i++) {
1030 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1031 }
1032
1033 android::os::ParcelFileDescriptor out;
1034 auto status = proc.rootIface->concatFiles(files, &out);
1035 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1036}
1037
Andrei Homescufc221502022-10-08 03:51:17 +00001038TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001039 if (socketType() == SocketType::TIPC) {
1040 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1041 }
1042
Andrei Homescufc221502022-10-08 03:51:17 +00001043 auto proc = createRpcTestSocketServerProcess({
1044 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1045 .serverSupportedFileDescriptorTransportModes =
1046 {RpcSession::FileDescriptorTransportMode::UNIX},
1047 });
1048
1049 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1050 ASSERT_NE(badFd, -1);
1051
1052 // Close the file descriptor so it becomes invalid for dup
1053 close(badFd);
1054
1055 Parcel p1;
1056 p1.markForBinder(proc.rootBinder);
1057 p1.writeInt32(3);
1058 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1059
1060 Parcel pRaw;
1061 pRaw.markForBinder(proc.rootBinder);
1062 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1063
1064 pRaw.setDataPosition(0);
1065 EXPECT_EQ(3, pRaw.readInt32());
1066 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1067}
1068
Andrei Homescu68a55612022-08-02 01:25:15 +00001069#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001070TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001071 if constexpr (!kEnableSharedLibs) {
1072 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1073 }
1074
Steven Moreland4313d7e2021-07-15 23:41:22 +00001075 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001076
1077 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1078 ASSERT_NE(binder, nullptr);
1079
1080 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1081}
1082
1083TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001084 if constexpr (!kEnableSharedLibs) {
1085 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1086 }
1087
Steven Moreland4313d7e2021-07-15 23:41:22 +00001088 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001089
1090 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1091 ASSERT_NE(binder, nullptr);
1092
1093 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1094 ASSERT_NE(ndkBinder, nullptr);
1095
1096 std::string out;
1097 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1098 ASSERT_TRUE(status.isOk()) << status.getDescription();
1099 ASSERT_EQ("aoeuaoeu", out);
1100}
Andrei Homescu68a55612022-08-02 01:25:15 +00001101#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001102
Steven Moreland5553ac42020-11-11 02:14:45 +00001103ssize_t countFds() {
1104 DIR* dir = opendir("/proc/self/fd/");
1105 if (dir == nullptr) return -1;
1106 ssize_t ret = 0;
1107 dirent* ent;
1108 while ((ent = readdir(dir)) != nullptr) ret++;
1109 closedir(dir);
1110 return ret;
1111}
1112
Andrei Homescua858b0e2022-08-01 23:43:09 +00001113TEST_P(BinderRpc, Fds) {
1114 if (serverSingleThreaded()) {
1115 GTEST_SKIP() << "This test requires multiple threads";
1116 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001117 if (socketType() == SocketType::TIPC) {
1118 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1119 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001120
Steven Moreland5553ac42020-11-11 02:14:45 +00001121 ssize_t beforeFds = countFds();
1122 ASSERT_GE(beforeFds, 0);
1123 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001124 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001125 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1126 }
1127 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1128}
1129
Andrei Homescud65666d2023-03-03 07:28:02 +00001130#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001131
1132static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1133 std::vector<BinderRpc::ParamType> ret;
1134
1135 for (const auto& clientVersion : testVersions()) {
1136 for (const auto& serverVersion : testVersions()) {
1137 ret.push_back(BinderRpc::ParamType{
1138 .type = SocketType::TIPC,
1139 .security = RpcSecurity::RAW,
1140 .clientVersion = clientVersion,
1141 .serverVersion = serverVersion,
1142 .singleThreaded = true,
1143 .noKernel = true,
1144 });
1145 }
1146 }
1147
1148 return ret;
1149}
1150
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001151INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1152 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001153#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001154bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001155 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001156 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001157
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001158 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001159 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001160
1161 if (errno == EAFNOSUPPORT) {
1162 return false;
1163 }
1164
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001165 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001166
1167 sockaddr_vm serverAddr{
1168 .svm_family = AF_VSOCK,
1169 .svm_port = vsockPort,
1170 .svm_cid = VMADDR_CID_ANY,
1171 };
1172 int ret = TEMP_FAILURE_RETRY(
1173 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1174 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1175 strerror(errno));
1176
1177 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1178 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1179 strerror(errno));
1180
1181 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1182 // to see if the kernel supports it. It's safe to use a blocking
1183 // connect because vsock sockets have a 2 second connection timeout,
1184 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001185 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001186 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001187 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
Andrei Homescu992a4052022-06-28 21:26:18 +00001188 strerror(errno));
1189
1190 bool success = false;
1191 sockaddr_vm connectAddr{
1192 .svm_family = AF_VSOCK,
1193 .svm_port = vsockPort,
1194 .svm_cid = VMADDR_CID_LOCAL,
1195 };
1196 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1197 sizeof(connectAddr)));
1198 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001199 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001200 while (true) {
1201 pollfd pfd[]{
1202 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1203 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1204 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001205 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001206 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1207
1208 if (pfd[0].revents & POLLIN) {
1209 sockaddr_vm acceptAddr;
1210 socklen_t acceptAddrLen = sizeof(acceptAddr);
1211 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1212 reinterpret_cast<sockaddr*>(&acceptAddr),
1213 &acceptAddrLen, SOCK_CLOEXEC));
1214 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1215 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1216 "Truncated address");
1217
1218 // Store the fd in acceptFd so we keep the connection alive
1219 // while polling connectFd
1220 acceptFd.reset(ret);
1221 }
1222
1223 if (pfd[1].revents & POLLOUT) {
1224 // Connect either succeeded or timed out
1225 int connectErrno;
1226 socklen_t connectErrnoLen = sizeof(connectErrno);
1227 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1228 &connectErrnoLen);
1229 LOG_ALWAYS_FATAL_IF(ret == -1,
1230 "Could not getsockopt() after connect() "
1231 "on non-blocking socket: %s.",
1232 strerror(errno));
1233
1234 // We're done, this is all we wanted
1235 success = connectErrno == 0;
1236 break;
1237 }
1238 }
1239 } else {
1240 success = ret == 0;
1241 }
1242
1243 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1244
1245 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001246}
1247
Yifan Hong1deca4b2021-09-10 16:16:44 -07001248static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001249 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1250 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001251
1252 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001253
Steven Moreland9f250b02023-05-16 23:27:42 +00001254#ifdef __BIONIC__
1255 // Devices may not have vsock support. AVF tests will verify whether they do, but
1256 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001257 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001258#else
1259 // On host machines, we always assume we have vsock loopback. If we don't, the
1260 // subsequent failures will be more clear than showing one now.
1261 static bool hasVsockLoopback = true;
1262#endif
Steven Morelandda573042021-06-12 01:13:45 +00001263
1264 if (hasVsockLoopback) {
1265 ret.push_back(SocketType::VSOCK);
1266 }
1267
1268 return ret;
1269}
1270
Steven Morelandb469f432023-07-28 22:13:47 +00001271static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1272 std::vector<BinderRpc::ParamType> ret;
1273
Steven Morelandf7421432023-07-28 22:41:44 +00001274 constexpr bool full = false;
1275
Steven Morelandb469f432023-07-28 22:13:47 +00001276 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001277 if (full || type == SocketType::UNIX) {
1278 for (const auto& security : RpcSecurityValues()) {
1279 for (const auto& clientVersion : testVersions()) {
1280 for (const auto& serverVersion : testVersions()) {
1281 for (bool singleThreaded : {false, true}) {
1282 for (bool noKernel : {false, true}) {
1283 ret.push_back(BinderRpc::ParamType{
1284 .type = type,
1285 .security = security,
1286 .clientVersion = clientVersion,
1287 .serverVersion = serverVersion,
1288 .singleThreaded = singleThreaded,
1289 .noKernel = noKernel,
1290 });
1291 }
Steven Morelandb469f432023-07-28 22:13:47 +00001292 }
1293 }
1294 }
1295 }
Steven Morelandf7421432023-07-28 22:41:44 +00001296 } else {
1297 ret.push_back(BinderRpc::ParamType{
1298 .type = type,
1299 .security = RpcSecurity::RAW,
1300 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1301 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1302 .singleThreaded = false,
1303 .noKernel = false,
1304 });
Steven Morelandb469f432023-07-28 22:13:47 +00001305 }
1306 }
Steven Morelandf7421432023-07-28 22:41:44 +00001307
Steven Morelandb469f432023-07-28 22:13:47 +00001308 return ret;
1309}
1310
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001311INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1312 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001313
Yifan Hong702115c2021-06-24 15:39:18 -07001314class BinderRpcServerRootObject
1315 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001316
1317TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1318 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1319 auto setRootObject = [](bool isStrong) -> SetFn {
1320 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1321 };
1322
Yifan Hong702115c2021-06-24 15:39:18 -07001323 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001324 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001325 auto binder1 = sp<BBinder>::make();
1326 IBinder* binderRaw1 = binder1.get();
1327 setRootObject(isStrong1)(server.get(), binder1);
1328 EXPECT_EQ(binderRaw1, server->getRootObject());
1329 binder1.clear();
1330 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1331
1332 auto binder2 = sp<BBinder>::make();
1333 IBinder* binderRaw2 = binder2.get();
1334 setRootObject(isStrong2)(server.get(), binder2);
1335 EXPECT_EQ(binderRaw2, server->getRootObject());
1336 binder2.clear();
1337 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1338}
1339
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001340INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1341 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1342 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001343
Yifan Hong1a235852021-05-13 16:07:47 -07001344class OneOffSignal {
1345public:
1346 // If notify() was previously called, or is called within |duration|, return true; else false.
1347 template <typename R, typename P>
1348 bool wait(std::chrono::duration<R, P> duration) {
1349 std::unique_lock<std::mutex> lock(mMutex);
1350 return mCv.wait_for(lock, duration, [this] { return mValue; });
1351 }
1352 void notify() {
1353 std::unique_lock<std::mutex> lock(mMutex);
1354 mValue = true;
1355 lock.unlock();
1356 mCv.notify_all();
1357 }
1358
1359private:
1360 std::mutex mMutex;
1361 std::condition_variable mCv;
1362 bool mValue = false;
1363};
1364
Yifan Hong194acf22021-06-29 18:44:56 -07001365TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001366 bool expectDebuggable = false;
1367#if defined(__ANDROID__)
1368 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1369 android::base::GetProperty("ro.build.type", "") != "user";
1370#else
Yifan Hong194acf22021-06-29 18:44:56 -07001371 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1372 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1373 "to binderHostDeviceTest. Hence, just disable this test on host.";
1374#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001375 if constexpr (!kEnableKernelIpc) {
1376 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1377 "at build time.";
1378 }
1379
Yifan Hong194acf22021-06-29 18:44:56 -07001380 sp<IServiceManager> sm = defaultServiceManager();
1381 ASSERT_NE(nullptr, sm);
1382 // Any Java service with non-empty getInterfaceDescriptor() would do.
1383 // Let's pick batteryproperties.
1384 auto binder = sm->checkService(String16("batteryproperties"));
1385 ASSERT_NE(nullptr, binder);
1386 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001387 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001388 ASSERT_EQ(OK, binder->pingBinder());
1389
1390 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001391 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001392 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001393 auto socket = rpcServer->releaseServer();
1394
1395 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001396 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1397
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001398 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001399 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001400 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1401 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001402 << statusToString(setRpcClientDebugStatus);
1403 GTEST_SKIP();
1404 }
1405
1406 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001407
1408 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001409 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001410 auto rpcBinder = rpcSession->getRootObject();
1411 ASSERT_NE(nullptr, rpcBinder);
1412
1413 ASSERT_EQ(OK, rpcBinder->pingBinder());
1414
1415 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1416 << "getInterfaceDescriptor should not crash system_server";
1417 ASSERT_EQ(OK, rpcBinder->pingBinder());
1418}
1419
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001420class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1421public:
1422 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001423 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001424 std::to_string(std::get<1>(info.param));
1425 }
1426};
1427
1428TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001429 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001430 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001431 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001432 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001433 ASSERT_FALSE(server->hasServer());
1434 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1435 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001436 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001437 ASSERT_FALSE(server->hasServer());
1438 ASSERT_EQ(sinkFd, retrieved.get());
1439}
1440
1441TEST_P(BinderRpcServerOnly, Shutdown) {
1442 if constexpr (!kEnableRpcThreads) {
1443 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1444 }
1445
1446 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001447 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001448 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001449 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1450 auto joinEnds = std::make_shared<OneOffSignal>();
1451
1452 // If things are broken and the thread never stops, don't block other tests. Because the thread
1453 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1454 // shared pointers are passed.
1455 std::thread([server, joinEnds] {
1456 server->join();
1457 joinEnds->notify();
1458 }).detach();
1459
1460 bool shutdown = false;
1461 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001462 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001463 if (server->shutdown()) shutdown = true;
1464 }
1465 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1466
1467 ASSERT_TRUE(joinEnds->wait(2s))
1468 << "After server->shutdown() returns true, join() did not stop after 2s";
1469}
1470
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001471INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1472 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1473 ::testing::ValuesIn(testVersions())),
1474 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001475
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001476class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001477public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001478 // Only parameterized only server version because `RpcSession` is bypassed
1479 // in the client half of the tests.
1480 using Param =
1481 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001482 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001483
1484 // A server that handles client socket connections.
1485 class Server {
1486 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001487 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001488
Yifan Hong1deca4b2021-09-10 16:16:44 -07001489 explicit Server() {}
1490 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001491 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001492 [[nodiscard]] AssertionResult setUp(
1493 const Param& param,
1494 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001495 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001496 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001497 if (!rpcServer->setProtocolVersion(serverVersion)) {
1498 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1499 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001500 switch (socketType) {
1501 case SocketType::PRECONNECTED: {
1502 return AssertionFailure() << "Not supported by this test";
1503 } break;
1504 case SocketType::UNIX: {
1505 auto addr = allocateSocketAddress();
1506 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1507 if (status != OK) {
1508 return AssertionFailure()
1509 << "setupUnixDomainServer: " << statusToString(status);
1510 }
1511 mConnectToServer = [addr] {
1512 return connectTo(UnixSocketAddress(addr.c_str()));
1513 };
1514 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001515 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001516 unique_fd bootstrapFdClient, bootstrapFdServer;
1517 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001518 return AssertionFailure() << "Socketpair() failed";
1519 }
1520 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1521 std::move(bootstrapFdServer));
1522 if (status != OK) {
1523 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1524 << statusToString(status);
1525 }
1526 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1527 mAcceptConnection = &Server::recvmsgServerConnection;
1528 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1529 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001530 case SocketType::UNIX_RAW: {
1531 auto addr = allocateSocketAddress();
1532 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1533 if (status != OK) {
1534 return AssertionFailure()
1535 << "setupRawSocketServer: " << statusToString(status);
1536 }
1537 mConnectToServer = [addr] {
1538 return connectTo(UnixSocketAddress(addr.c_str()));
1539 };
1540 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001541 case SocketType::VSOCK: {
1542 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001543 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001544 if (status != OK) {
1545 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1546 }
1547 mConnectToServer = [port] {
1548 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1549 };
1550 } break;
1551 case SocketType::INET: {
1552 unsigned int port;
1553 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1554 if (status != OK) {
1555 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1556 }
1557 mConnectToServer = [port] {
1558 const char* addr = kLocalInetAddress;
1559 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001560 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001561 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1562 auto fd = connectTo(
1563 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1564 if (fd.ok()) return fd;
1565 }
1566 ALOGE("None of the socket address resolved for %s:%u can be connected",
1567 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001568 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001569 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001570 } break;
1571 case SocketType::TIPC: {
1572 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1573 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001574 }
1575 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001576 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001577 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001578 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1579 mSetup = true;
1580 return AssertionSuccess();
1581 }
1582 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1583 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1584 return mCertVerifier;
1585 }
1586 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1587 void start() {
1588 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1589 mThread = std::make_unique<std::thread>(&Server::run, this);
1590 }
David Brazdil21c887c2022-09-23 12:25:18 +01001591
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001592 unique_fd acceptServerConnection() {
1593 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001594 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1595 }
1596
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001597 unique_fd recvmsgServerConnection() {
1598 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001599 int buf;
1600 iovec iov{&buf, sizeof(buf)};
1601
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001602 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001603 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001604 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001605 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1606 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001607 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001608 }
1609
Yifan Hong1deca4b2021-09-10 16:16:44 -07001610 void run() {
1611 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1612
1613 std::vector<std::thread> threads;
1614 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001615 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001616 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1617 }
1618
1619 for (auto& thread : threads) thread.join();
1620 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001621 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001622 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001623 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001624 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001626 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001627 }
Yifan Honge07d2732021-09-13 21:59:14 -07001628 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001629 shutdown();
1630 join();
1631 }
1632 void shutdown() { mFdTrigger->trigger(); }
1633
1634 void setPostConnect(
1635 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1636 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637 }
1638
1639 private:
1640 std::unique_ptr<std::thread> mThread;
1641 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001642 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001643 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001644 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001645 std::unique_ptr<RpcTransportCtx> mCtx;
1646 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1647 std::make_shared<RpcCertificateVerifierSimple>();
1648 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001649 // The function invoked after connection and handshake. By default, it is
1650 // |defaultPostConnect| that sends |kMessage| to the client.
1651 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1652 Server::defaultPostConnect;
1653
1654 void join() {
1655 if (mThread != nullptr) {
1656 mThread->join();
1657 mThread = nullptr;
1658 }
1659 }
1660
1661 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1662 FdTrigger* fdTrigger) {
1663 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001664 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001665 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001666 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001667 if (status != OK) return AssertionFailure() << statusToString(status);
1668 return AssertionSuccess();
1669 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001670 };
1671
1672 class Client {
1673 public:
1674 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1675 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001676 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001677 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1678 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001679 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001680 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001681 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1682 return AssertionSuccess();
1683 }
1684 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1685 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1686 return mCertVerifier;
1687 }
Yifan Hong67519322021-09-13 18:51:16 -07001688 // connect() and do handshake
1689 bool setUpTransport() {
1690 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001691 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001692 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1693 return mClientTransport != nullptr;
1694 }
1695 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1696 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1697 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001698 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001699 status_t readStatus =
1700 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001701 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001702 if (readStatus != OK) {
1703 return AssertionFailure() << statusToString(readStatus);
1704 }
1705 if (readMessage != expectedMessage) {
1706 return AssertionFailure()
1707 << "Expected " << expectedMessage << ", actual " << readMessage;
1708 }
1709 return AssertionSuccess();
1710 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001711 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001712 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001713 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1714 return;
1715 }
1716 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001717 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718 }
1719
Pawan49d74cb2022-08-03 21:19:11 +00001720 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1721
Yifan Hong1deca4b2021-09-10 16:16:44 -07001722 private:
1723 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001724 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001725 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1726 std::unique_ptr<RpcTransportCtx> mCtx;
1727 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1728 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001729 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730 };
1731
1732 // Make A trust B.
1733 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001734 static status_t trust(RpcSecurity rpcSecurity,
1735 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1736 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001737 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001738 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1739 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1740 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001741 }
1742
1743 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001744};
1745
1746class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1747public:
1748 using Server = RpcTransportTestUtils::Server;
1749 using Client = RpcTransportTestUtils::Client;
1750 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001751 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001752 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001754 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001755 return ret;
1756 }
1757 static std::vector<ParamType> getRpcTranportTestParams() {
1758 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001759 for (auto serverVersion : testVersions()) {
1760 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1761 for (auto rpcSecurity : RpcSecurityValues()) {
1762 switch (rpcSecurity) {
1763 case RpcSecurity::RAW: {
1764 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1765 } break;
1766 case RpcSecurity::TLS: {
1767 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1768 serverVersion);
1769 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1770 serverVersion);
1771 } break;
1772 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001773 }
1774 }
1775 }
1776 return ret;
1777 }
1778 template <typename A, typename B>
1779 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001780 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1781 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001782 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1783 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001784 void SetUp() override {
1785 if constexpr (!kEnableRpcThreads) {
1786 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1787 }
1788 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001789};
1790
1791TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001792 auto server = std::make_unique<Server>();
1793 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794
1795 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001796 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001797
1798 ASSERT_EQ(OK, trust(&client, server));
1799 ASSERT_EQ(OK, trust(server, &client));
1800
1801 server->start();
1802 client.run();
1803}
1804
1805TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001806 auto server = std::make_unique<Server>();
1807 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001808
1809 std::vector<Client> clients;
1810 for (int i = 0; i < 2; i++) {
1811 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001812 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001813 ASSERT_EQ(OK, trust(&client, server));
1814 ASSERT_EQ(OK, trust(server, &client));
1815 }
1816
1817 server->start();
1818 for (auto& client : clients) client.run();
1819}
1820
1821TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001822 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1823 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001825 auto untrustedServer = std::make_unique<Server>();
1826 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001827
1828 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001829 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001830
1831 ASSERT_EQ(OK, trust(untrustedServer, &client));
1832
1833 untrustedServer->start();
1834
1835 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1836 // the client can't verify the server's identity.
1837 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1838 client.run(handshakeOk);
1839}
1840TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001841 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1842 (void)serverVersion;
1843
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001844 auto validServer = std::make_unique<Server>();
1845 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001846
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001847 auto maliciousServer = std::make_unique<Server>();
1848 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001849
1850 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001851 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001852
1853 ASSERT_EQ(OK, trust(&client, validServer));
1854 ASSERT_EQ(OK, trust(validServer, &client));
1855 ASSERT_EQ(OK, trust(maliciousServer, &client));
1856
1857 maliciousServer->start();
1858
1859 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1860 // the client can't verify the server's identity.
1861 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1862 client.run(handshakeOk);
1863}
1864
1865TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001866 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1867 (void)serverVersion;
1868
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001869 auto server = std::make_unique<Server>();
1870 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871
1872 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001873 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001874
1875 ASSERT_EQ(OK, trust(&client, server));
1876
1877 server->start();
1878
1879 // For TLS, Client should be able to verify server's identity, so client should see
1880 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1881 // identity and should drop the connection, so client shouldn't be able to read anything.
1882 bool readOk = rpcSecurity != RpcSecurity::TLS;
1883 client.run(true, readOk);
1884}
1885
1886TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001887 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1888 (void)serverVersion;
1889
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001890 auto server = std::make_unique<Server>();
1891 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001892
1893 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001894 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001896 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001897
1898 ASSERT_EQ(OK, trust(&validClient, server));
1899 ASSERT_EQ(OK, trust(&maliciousClient, server));
1900
1901 server->start();
1902
1903 // See UntrustedClient.
1904 bool readOk = rpcSecurity != RpcSecurity::TLS;
1905 maliciousClient.run(true, readOk);
1906}
1907
Yifan Hong67519322021-09-13 18:51:16 -07001908TEST_P(RpcTransportTest, Trigger) {
1909 std::string msg2 = ", world!";
1910 std::mutex writeMutex;
1911 std::condition_variable writeCv;
1912 bool shouldContinueWriting = false;
1913 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001914 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001915 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001916 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1917 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001918 if (status != OK) return AssertionFailure() << statusToString(status);
1919
1920 {
1921 std::unique_lock<std::mutex> lock(writeMutex);
1922 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1923 return AssertionFailure() << "write barrier not cleared in time!";
1924 }
1925 }
1926
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001927 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001928 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1929 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001930 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001931 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001932 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001933 << statusToString(status);
1934 return AssertionSuccess();
1935 };
1936
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 auto server = std::make_unique<Server>();
1938 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001939
1940 // Set up client
1941 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001942 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001943
1944 // Exchange keys
1945 ASSERT_EQ(OK, trust(&client, server));
1946 ASSERT_EQ(OK, trust(server, &client));
1947
1948 server->setPostConnect(serverPostConnect);
1949
Yifan Hong67519322021-09-13 18:51:16 -07001950 server->start();
1951 // connect() to server and do handshake
1952 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001953 // read the first message. This ensures that server has finished handshake and start handling
1954 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001955 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001956 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1957 // write is on an FdTrigger that has been shut down.
1958 server->shutdown();
1959 // Continues server thread to write the second message.
1960 {
Yifan Hong22211f82021-09-14 12:32:25 -07001961 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001962 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001963 }
Yifan Hong22211f82021-09-14 12:32:25 -07001964 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001965 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001966 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001967 // On the client side, second read fails with DEAD_OBJECT
1968 ASSERT_FALSE(client.readMessage(msg2));
1969}
1970
Pawan49d74cb2022-08-03 21:19:11 +00001971TEST_P(RpcTransportTest, CheckWaitingForRead) {
1972 std::mutex readMutex;
1973 std::condition_variable readCv;
1974 bool shouldContinueReading = false;
1975 // Server will write data on transport once its started
1976 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1977 std::string message(RpcTransportTestUtils::kMessage);
1978 iovec messageIov{message.data(), message.size()};
1979 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1980 std::nullopt, nullptr);
1981 if (status != OK) return AssertionFailure() << statusToString(status);
1982
1983 {
1984 std::unique_lock<std::mutex> lock(readMutex);
1985 shouldContinueReading = true;
1986 lock.unlock();
1987 readCv.notify_all();
1988 }
1989 return AssertionSuccess();
1990 };
1991
1992 // Setup Server and client
1993 auto server = std::make_unique<Server>();
1994 ASSERT_TRUE(server->setUp(GetParam()));
1995
1996 Client client(server->getConnectToServerFn());
1997 ASSERT_TRUE(client.setUp(GetParam()));
1998
1999 ASSERT_EQ(OK, trust(&client, server));
2000 ASSERT_EQ(OK, trust(server, &client));
2001 server->setPostConnect(serverPostConnect);
2002
2003 server->start();
2004 ASSERT_TRUE(client.setUpTransport());
2005 {
2006 // Wait till server writes data
2007 std::unique_lock<std::mutex> lock(readMutex);
2008 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2009 }
2010
2011 // Since there is no read polling here, we will get polling count 0
2012 ASSERT_FALSE(client.isTransportWaiting());
2013 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2014 // Thread should increment polling count, read and decrement polling count
2015 // Again, polling count should be zero here
2016 ASSERT_FALSE(client.isTransportWaiting());
2017
2018 server->shutdown();
2019}
2020
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002021INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2022 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2023 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002024
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002026 : public testing::TestWithParam<
2027 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002028public:
2029 template <typename A, typename B>
2030 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002031 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2032 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002033 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2034 }
2035 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002036 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2037 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2038 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002039 };
2040};
2041
2042TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002043 if constexpr (!kEnableRpcThreads) {
2044 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2045 }
2046
Frederick Mayledc07cf82022-05-26 20:30:12 +00002047 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002048
2049 std::vector<uint8_t> pkeyData, certData;
2050 {
2051 auto pkey = makeKeyPairForSelfSignedCert();
2052 ASSERT_NE(nullptr, pkey);
2053 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2054 ASSERT_NE(nullptr, cert);
2055 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2056 certData = serializeCertificate(cert.get(), certificateFormat);
2057 }
2058
2059 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2060 auto desCert = deserializeCertificate(certData, certificateFormat);
2061 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002062 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2063 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002064
2065 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2066 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2067
2068 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2069 ASSERT_TRUE(client.setUp(utilsParam));
2070
2071 ASSERT_EQ(OK, trust(&client, server));
2072 ASSERT_EQ(OK, trust(server, &client));
2073
2074 server->start();
2075 client.run();
2076}
2077
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002078INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002079 BinderRpc, RpcTransportTlsKeyTest,
2080 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2081 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002082 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2083 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002084 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002085#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002086
Steven Morelandc1635952021-04-01 16:20:47 +00002087} // namespace android
2088
2089int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002090 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002091 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002092
Steven Moreland5553ac42020-11-11 02:14:45 +00002093 return RUN_ALL_TESTS();
2094}