blob: c044d3943d5976070bc00947ca30905e49b6ebb4 [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 Wasilczyk68c42082024-05-20 11:59:35 -070067 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000068 }
69 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070070 return "term signal " + std::to_string(WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000071 }
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070072 return "unexpected state " + std::to_string(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 Wasilczyk68c42082024-05-20 11:59:35 -0700266 auto servicePath = path + "/binder_rpc_test_service" +
267 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "");
Andrei Homescu96834632022-10-14 00:49:49 +0000268
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700269 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000270
Alice Wang893a9912022-10-24 10:44:09 +0000271 auto addr = allocateSocketAddress();
272 // Initializes the socket before the fork/exec.
273 if (socketType == SocketType::UNIX_RAW) {
274 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000275 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
276 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
277 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700278 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700279 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000280 }
Alice Wang893a9912022-10-24 10:44:09 +0000281 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000282
Andrei Homescu96834632022-10-14 00:49:49 +0000283 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700284 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000285 if (socketType == SocketType::TIPC) {
286 // Trusty has a single persistent service
287 return;
288 }
289
Andrei Homescu96834632022-10-14 00:49:49 +0000290 auto writeFd = std::to_string(writeEnd.get());
291 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800292 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
293 readFd.c_str(), NULL);
294 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
295 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000296 }));
297
298 BinderRpcTestServerConfig serverConfig;
299 serverConfig.numThreads = options.numThreads;
300 serverConfig.socketType = static_cast<int32_t>(socketType);
301 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
302 serverConfig.serverVersion = serverVersion;
303 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000304 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000305 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000306 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
307 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
308 static_cast<int32_t>(mode));
309 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000310 if (socketType != SocketType::TIPC) {
311 writeToFd(ret->host.writeEnd(), serverConfig);
312 }
Andrei Homescu96834632022-10-14 00:49:49 +0000313
314 std::vector<sp<RpcSession>> sessions;
315 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
316 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000317 std::unique_ptr<RpcTransportCtxFactory> factory;
318 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000319#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000320 factory = RpcTransportCtxFactoryTipcAndroid::make();
321#else
322 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
323#endif
324 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000325 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000326 }
327 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100328 }
329
Andrei Homescu68a55612022-08-02 01:25:15 +0000330 BinderRpcTestServerInfo serverInfo;
331 if (socketType != SocketType::TIPC) {
332 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
333 BinderRpcTestClientInfo clientInfo;
334 for (const auto& session : sessions) {
335 auto& parcelableCert = clientInfo.certs.emplace_back();
336 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
337 }
338 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000339
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700340 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000341 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700342 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000343 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000344
Andrei Homescu68a55612022-08-02 01:25:15 +0000345 if (rpcSecurity == RpcSecurity::TLS) {
346 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700347 LOG_ALWAYS_FATAL_IF(
348 OK !=
349 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000350 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700351 }
352
Andrei Homescu96834632022-10-14 00:49:49 +0000353 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000354
Steven Moreland67f85902023-03-15 01:13:49 +0000355 for (size_t i = 0; i < sessions.size(); i++) {
356 const auto& session = sessions.at(i);
357
358 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
359 ? options.numIncomingConnectionsBySession.at(i)
360 : 0;
361
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700362 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000363 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000364 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000365 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000366
Andrei Homescu96834632022-10-14 00:49:49 +0000367 switch (socketType) {
368 case SocketType::PRECONNECTED:
369 status = session->setupPreconnectedClient({}, [=]() {
370 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
371 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000372 break;
Alice Wang893a9912022-10-24 10:44:09 +0000373 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000374 case SocketType::UNIX:
375 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
376 break;
377 case SocketType::UNIX_BOOTSTRAP:
378 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700379 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000380 break;
381 case SocketType::VSOCK:
382 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
383 break;
384 case SocketType::INET:
385 status = session->setupInetClient("127.0.0.1", serverInfo.port);
386 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000387 case SocketType::TIPC:
388 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000389#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000390 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000391 for (size_t i = 0; i < 5; i++) {
392 // Try to connect several times,
393 // in case the service is slow to start
394 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
395 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700396 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000397 }
398 usleep(50000);
399 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700400 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000401#else
402 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700403 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000404#endif
405 });
406 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000407 default:
408 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000409 }
Andrei Homescu96834632022-10-14 00:49:49 +0000410 if (options.allowConnectFailure && status != OK) {
411 ret->sessions.clear();
412 break;
413 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700414 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Andrei Homescu96834632022-10-14 00:49:49 +0000415 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000416 }
Andrei Homescu96834632022-10-14 00:49:49 +0000417 return ret;
418}
Steven Morelandc1635952021-04-01 16:20:47 +0000419
Andrei Homescua858b0e2022-08-01 23:43:09 +0000420TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
421 if (clientOrServerSingleThreaded()) {
422 GTEST_SKIP() << "This test requires multiple threads";
423 }
424
Steven Moreland5553ac42020-11-11 02:14:45 +0000425 constexpr size_t kNumThreads = 10;
426
Steven Moreland4313d7e2021-07-15 23:41:22 +0000427 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000428
429 EXPECT_OK(proc.rootIface->lock());
430
431 // block all but one thread taking locks
432 std::vector<std::thread> ts;
433 for (size_t i = 0; i < kNumThreads - 1; i++) {
434 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
435 }
436
Steven Morelandd6d816f2022-12-23 01:37:17 +0000437 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000438
439 // other calls still work
440 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
441
Steven Morelandd6d816f2022-12-23 01:37:17 +0000442 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 size_t epochMsBefore = epochMillis();
444 // after this, we should never see a response within this time
445 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
446
447 // this call should be blocked for blockTimeMs
448 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
449
450 size_t epochMsAfter = epochMillis();
451 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
452
453 for (auto& t : ts) t.join();
454}
455
Steven Moreland27f620a2023-03-06 19:44:36 +0000456static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 size_t epochMsBefore = epochMillis();
458
459 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700460 for (size_t i = 0; i < numCalls; i++) {
461 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 }
463
464 for (auto& t : ts) t.join();
465
466 size_t epochMsAfter = epochMillis();
467
Yifan Hong1f44f982021-10-08 17:16:47 -0700468 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000469
Steven Moreland9c203222023-05-31 21:26:41 +0000470 // Potential flake, but make sure calls are handled in parallel. Due
471 // to past flakes, this only checks that the amount of time taken has
472 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
473 // check this more exactly.
474 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700475}
476
Andrei Homescua858b0e2022-08-01 23:43:09 +0000477TEST_P(BinderRpc, ThreadPoolOverSaturated) {
478 if (clientOrServerSingleThreaded()) {
479 GTEST_SKIP() << "This test requires multiple threads";
480 }
481
Yifan Hong1f44f982021-10-08 17:16:47 -0700482 constexpr size_t kNumThreads = 10;
483 constexpr size_t kNumCalls = kNumThreads + 3;
484 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000485
486 // b/272429574 - below 500ms, the test fails
487 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700488}
489
Andrei Homescua858b0e2022-08-01 23:43:09 +0000490TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
491 if (clientOrServerSingleThreaded()) {
492 GTEST_SKIP() << "This test requires multiple threads";
493 }
494
Yifan Hong1f44f982021-10-08 17:16:47 -0700495 constexpr size_t kNumThreads = 20;
496 constexpr size_t kNumOutgoingConnections = 10;
497 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
498 auto proc = createRpcTestSocketServerProcess(
499 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000500
501 // b/272429574 - below 500ms, the test fails
502 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000503}
504
Andrei Homescua858b0e2022-08-01 23:43:09 +0000505TEST_P(BinderRpc, ThreadingStressTest) {
506 if (clientOrServerSingleThreaded()) {
507 GTEST_SKIP() << "This test requires multiple threads";
508 }
509
Steven Moreland27f620a2023-03-06 19:44:36 +0000510 constexpr size_t kNumClientThreads = 5;
511 constexpr size_t kNumServerThreads = 5;
512 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000513
Steven Moreland4313d7e2021-07-15 23:41:22 +0000514 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000515
516 std::vector<std::thread> threads;
517 for (size_t i = 0; i < kNumClientThreads; i++) {
518 threads.push_back(std::thread([&] {
519 for (size_t j = 0; j < kNumCalls; j++) {
520 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000521 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000522 EXPECT_EQ(proc.rootBinder, out);
523 }
524 }));
525 }
526
527 for (auto& t : threads) t.join();
528}
529
Steven Moreland925ba0a2021-09-17 18:06:32 -0700530static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
531 std::vector<std::thread> threads;
532 for (size_t i = 0; i < threadCount; i++) {
533 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
534 }
535 for (auto& t : threads) t.join();
536}
537
Andrei Homescua858b0e2022-08-01 23:43:09 +0000538TEST_P(BinderRpc, OnewayStressTest) {
539 if (clientOrServerSingleThreaded()) {
540 GTEST_SKIP() << "This test requires multiple threads";
541 }
542
Steven Morelandc6046982021-04-20 00:49:42 +0000543 constexpr size_t kNumClientThreads = 10;
544 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700545 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000546
Steven Moreland4313d7e2021-07-15 23:41:22 +0000547 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000548
549 std::vector<std::thread> threads;
550 for (size_t i = 0; i < kNumClientThreads; i++) {
551 threads.push_back(std::thread([&] {
552 for (size_t j = 0; j < kNumCalls; j++) {
553 EXPECT_OK(proc.rootIface->sendString("a"));
554 }
Steven Morelandc6046982021-04-20 00:49:42 +0000555 }));
556 }
557
558 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700559
560 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000561}
562
Frederick Mayleb0221d12022-10-03 23:10:53 +0000563TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
564 if (!supportsFdTransport()) {
565 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
566 }
567 if (clientOrServerSingleThreaded()) {
568 GTEST_SKIP() << "This test requires multiple threads";
569 }
570
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000571 constexpr size_t kNumServerThreads = 3;
572
Frederick Mayleb0221d12022-10-03 23:10:53 +0000573 // This test forces a oneway transaction to be queued by issuing two
574 // `blockingSendFdOneway` calls, then drains the queue by issuing two
575 // `blockingRecvFd` calls.
576 //
577 // For more details about the queuing semantics see
578 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
579
580 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000581 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000582 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
583 .serverSupportedFileDescriptorTransportModes =
584 {RpcSession::FileDescriptorTransportMode::UNIX},
585 });
586
587 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
588 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
589 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
590 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
591
592 android::os::ParcelFileDescriptor fdA;
593 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
594 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700595 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000596 EXPECT_EQ(result, "a");
597
598 android::os::ParcelFileDescriptor fdB;
599 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700600 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000601 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000602
603 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000604}
605
Andrei Homescua858b0e2022-08-01 23:43:09 +0000606TEST_P(BinderRpc, OnewayCallQueueing) {
607 if (clientOrServerSingleThreaded()) {
608 GTEST_SKIP() << "This test requires multiple threads";
609 }
610
Frederick Mayle96872592023-03-07 14:56:15 -0800611 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000612 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000613
614 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000615 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000616
Frederick Mayle96872592023-03-07 14:56:15 -0800617 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700618 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800619 for (size_t i = 0; i + 1 < kNumQueued; i++) {
620 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000621 }
Frederick Mayle96872592023-03-07 14:56:15 -0800622 for (size_t i = 0; i + 1 < kNumQueued; i++) {
623 int n;
624 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700625 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800626 }
Steven Morelandf5174272021-05-25 00:39:28 +0000627
Steven Moreland925ba0a2021-09-17 18:06:32 -0700628 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000629}
630
Andrei Homescua858b0e2022-08-01 23:43:09 +0000631TEST_P(BinderRpc, OnewayCallExhaustion) {
632 if (clientOrServerSingleThreaded()) {
633 GTEST_SKIP() << "This test requires multiple threads";
634 }
635
Steven Morelandd45be622021-06-04 02:19:37 +0000636 constexpr size_t kNumClients = 2;
637 constexpr size_t kTooLongMs = 1000;
638
Steven Moreland4313d7e2021-07-15 23:41:22 +0000639 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000640
641 // Build up oneway calls on the second session to make sure it terminates
642 // and shuts down. The first session should be unaffected (proc destructor
643 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000644 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000645
646 std::vector<std::thread> threads;
647 for (size_t i = 0; i < kNumClients; i++) {
648 // one of these threads will get stuck queueing a transaction once the
649 // socket fills up, the other will be able to fill up transactions on
650 // this object
651 threads.push_back(std::thread([&] {
652 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
653 }
654 }));
655 }
656 for (auto& t : threads) t.join();
657
658 Status status = iface->sleepMsAsync(kTooLongMs);
659 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
660
Steven Moreland798e0d12021-07-14 23:19:25 +0000661 // now that it has died, wait for the remote session to shutdown
662 std::vector<int32_t> remoteCounts;
663 do {
664 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
665 } while (remoteCounts.size() == kNumClients);
666
Steven Morelandd45be622021-06-04 02:19:37 +0000667 // the second session should be shutdown in the other process by the time we
668 // are able to join above (it'll only be hung up once it finishes processing
669 // any pending commands). We need to erase this session from the record
670 // here, so that the destructor for our session won't check that this
671 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000672 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000673}
674
Steven Moreland67f85902023-03-15 01:13:49 +0000675TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
676 if (clientOrServerSingleThreaded()) {
677 GTEST_SKIP() << "This test requires multiple threads";
678 }
679
680 // session 0 - will check for leaks in destrutor of proc
681 // session 1 - we want to make sure it gets deleted when we drop all references to it
682 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700683 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000684
685 wp<RpcSession> session = proc.proc->sessions.at(1).session;
686
687 // remove all references to the second session
688 proc.proc->sessions.at(1).root = nullptr;
689 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
690
691 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
692 // to drain commands.
693 for (size_t i = 0; i < 100; i++) {
694 usleep(10 * 1000);
695 if (session.promote() == nullptr) break;
696 }
697
698 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000699
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000700 // now that it has died, wait for the remote session to shutdown
701 std::vector<int32_t> remoteCounts;
702 do {
703 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
704 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000705}
706
Devin Moore66d5b7a2022-07-07 21:42:10 +0000707TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000708 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000709 GTEST_SKIP() << "This test requires multiple threads";
710 }
711 class MyDeathRec : public IBinder::DeathRecipient {
712 public:
713 void binderDied(const wp<IBinder>& /* who */) override {
714 dead = true;
715 mCv.notify_one();
716 }
717 std::mutex mMtx;
718 std::condition_variable mCv;
719 bool dead = false;
720 };
721
722 // Death recipient needs to have an incoming connection to be called
723 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000724 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000725
726 auto dr = sp<MyDeathRec>::make();
727 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
728
729 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
730 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
731 }
732
733 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000734 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000735
736 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000737 // can't do this before checking the death recipient by calling
738 // forceShutdown earlier, because shutdownAndWait will also trigger
739 // a death recipient, but if we had a way to wait for the service
740 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000741 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000742 proc.expectAlreadyShutdown = true;
743}
744
745TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000746 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000747 GTEST_SKIP() << "This test requires multiple threads";
748 }
749 class MyDeathRec : public IBinder::DeathRecipient {
750 public:
751 void binderDied(const wp<IBinder>& /* who */) override {
752 dead = true;
753 mCv.notify_one();
754 }
755 std::mutex mMtx;
756 std::condition_variable mCv;
757 bool dead = false;
758 };
759
760 // Death recipient needs to have an incoming connection to be called
761 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000762 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000763
764 auto dr = sp<MyDeathRec>::make();
765 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
766
767 // Explicitly calling shutDownAndWait will cause the death recipients
768 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000769 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000770
771 std::unique_lock<std::mutex> lock(dr->mMtx);
772 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000773 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000774 }
775 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
776
Andrei Homescu96834632022-10-14 00:49:49 +0000777 proc.proc->terminate();
778 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000779 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
780 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
781 });
782 proc.expectAlreadyShutdown = true;
783}
784
Steven Moreland5ec743f2023-01-18 01:02:06 +0000785TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000786 if (socketType() == SocketType::TIPC) {
787 // This should work, but Trusty takes too long to restart the service
788 GTEST_SKIP() << "Service death test not supported on Trusty";
789 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000790 class MyDeathRec : public IBinder::DeathRecipient {
791 public:
792 void binderDied(const wp<IBinder>& /* who */) override {}
793 };
794
Steven Moreland67f85902023-03-15 01:13:49 +0000795 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000796
797 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000798 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000799}
800
801TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000802 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000803 GTEST_SKIP() << "This test requires multiple threads";
804 }
805 class MyDeathRec : public IBinder::DeathRecipient {
806 public:
807 void binderDied(const wp<IBinder>& /* who */) override {
808 GTEST_FAIL() << "This should not be called after unlinkToDeath";
809 }
810 };
811
812 // Death recipient needs to have an incoming connection to be called
813 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000814 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000815
816 auto dr = sp<MyDeathRec>::make();
817 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
818 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
819
Steven Moreland67f85902023-03-15 01:13:49 +0000820 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000821}
822
Steven Morelandc1635952021-04-01 16:20:47 +0000823TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000824 if (socketType() == SocketType::TIPC) {
825 // This should work, but Trusty takes too long to restart the service
826 GTEST_SKIP() << "Service death test not supported on Trusty";
827 }
828
Steven Moreland5553ac42020-11-11 02:14:45 +0000829 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000830 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000831
832 // make sure there is some state during crash
833 // 1. we hold their binder
834 sp<IBinderRpcSession> session;
835 EXPECT_OK(proc.rootIface->openSession("happy", &session));
836 // 2. they hold our binder
837 sp<IBinder> binder = new BBinder();
838 EXPECT_OK(proc.rootIface->holdBinder(binder));
839
840 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
841 << "Do death cleanup: " << doDeathCleanup;
842
Andrei Homescu96834632022-10-14 00:49:49 +0000843 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000844 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
845 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
846 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000847 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000848 }
849}
850
Steven Morelandd7302072021-05-15 01:32:04 +0000851TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000852 // This test only works if the current process shared the internal state of
853 // ProcessState with the service across the call to fork(). Both the static
854 // libraries and libbinder.so have their own separate copies of all the
855 // globals, so the test only works when the test client and service both use
856 // libbinder.so (when using static libraries, even a client and service
857 // using the same kind of static library should have separate copies of the
858 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000859 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000860 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
861 "at build time.";
862 }
863
Steven Moreland4313d7e2021-07-15 23:41:22 +0000864 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000865
Andrei Homescu2a298012022-06-15 01:08:54 +0000866 // we can't allocate IPCThreadState so actually the first time should
867 // succeed :(
868 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000869
870 // second time! we catch the error :)
871 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
872
Andrei Homescu96834632022-10-14 00:49:49 +0000873 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000874 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
875 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
876 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000877 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000878}
879
Frederick Mayle69a0c992022-05-26 20:38:39 +0000880TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000881 if (socketType() == SocketType::TIPC) {
882 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
883 }
884
Frederick Mayle69a0c992022-05-26 20:38:39 +0000885 auto proc = createRpcTestSocketServerProcess({
886 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
887 .serverSupportedFileDescriptorTransportModes =
888 {RpcSession::FileDescriptorTransportMode::UNIX},
889 .allowConnectFailure = true,
890 });
Andrei Homescu96834632022-10-14 00:49:49 +0000891 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
892 proc.proc->terminate();
893 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000894 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
895 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
896 });
897 proc.expectAlreadyShutdown = true;
898}
899
900TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000901 if (socketType() == SocketType::TIPC) {
902 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
903 }
904
Frederick Mayle69a0c992022-05-26 20:38:39 +0000905 auto proc = createRpcTestSocketServerProcess({
906 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
907 .serverSupportedFileDescriptorTransportModes =
908 {RpcSession::FileDescriptorTransportMode::NONE},
909 .allowConnectFailure = true,
910 });
Andrei Homescu96834632022-10-14 00:49:49 +0000911 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
912 proc.proc->terminate();
913 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000914 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
915 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
916 });
917 proc.expectAlreadyShutdown = true;
918}
919
920TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000921 if (socketType() == SocketType::TIPC) {
922 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
923 }
924
Frederick Mayle69a0c992022-05-26 20:38:39 +0000925 auto proc = createRpcTestSocketServerProcess({
926 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
927 .serverSupportedFileDescriptorTransportModes =
928 {RpcSession::FileDescriptorTransportMode::NONE,
929 RpcSession::FileDescriptorTransportMode::UNIX},
930 });
931
932 android::os::ParcelFileDescriptor out;
933 auto status = proc.rootIface->echoAsFile("hello", &out);
934 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
935}
936
937TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000938 if (socketType() == SocketType::TIPC) {
939 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
940 }
941
Frederick Mayle69a0c992022-05-26 20:38:39 +0000942 auto proc = createRpcTestSocketServerProcess({
943 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
944 .serverSupportedFileDescriptorTransportModes =
945 {RpcSession::FileDescriptorTransportMode::UNIX},
946 });
947
948 android::os::ParcelFileDescriptor out;
949 auto status = proc.rootIface->echoAsFile("hello", &out);
950 if (!supportsFdTransport()) {
951 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
952 return;
953 }
954 ASSERT_TRUE(status.isOk()) << status;
955
956 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700957 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700958 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000959}
960
961TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000962 if (socketType() == SocketType::TIPC) {
963 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
964 }
965
Frederick Mayle69a0c992022-05-26 20:38:39 +0000966 auto proc = createRpcTestSocketServerProcess({
967 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
968 .serverSupportedFileDescriptorTransportModes =
969 {RpcSession::FileDescriptorTransportMode::UNIX},
970 });
971
972 std::vector<android::os::ParcelFileDescriptor> files;
973 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
975 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
976 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
977
978 android::os::ParcelFileDescriptor out;
979 auto status = proc.rootIface->concatFiles(files, &out);
980 if (!supportsFdTransport()) {
981 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
982 return;
983 }
984 ASSERT_TRUE(status.isOk()) << status;
985
986 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700987 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000988 EXPECT_EQ(result, "123abcd");
989}
990
991TEST_P(BinderRpc, SendMaxFiles) {
992 if (!supportsFdTransport()) {
993 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
994 }
995
996 auto proc = createRpcTestSocketServerProcess({
997 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
998 .serverSupportedFileDescriptorTransportModes =
999 {RpcSession::FileDescriptorTransportMode::UNIX},
1000 });
1001
1002 std::vector<android::os::ParcelFileDescriptor> files;
1003 for (int i = 0; i < 253; i++) {
1004 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1005 }
1006
1007 android::os::ParcelFileDescriptor out;
1008 auto status = proc.rootIface->concatFiles(files, &out);
1009 ASSERT_TRUE(status.isOk()) << status;
1010
1011 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001012 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001013 EXPECT_EQ(result, std::string(253, 'a'));
1014}
1015
1016TEST_P(BinderRpc, SendTooManyFiles) {
1017 if (!supportsFdTransport()) {
1018 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1019 }
1020
1021 auto proc = createRpcTestSocketServerProcess({
1022 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1023 .serverSupportedFileDescriptorTransportModes =
1024 {RpcSession::FileDescriptorTransportMode::UNIX},
1025 });
1026
1027 std::vector<android::os::ParcelFileDescriptor> files;
1028 for (int i = 0; i < 254; i++) {
1029 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1030 }
1031
1032 android::os::ParcelFileDescriptor out;
1033 auto status = proc.rootIface->concatFiles(files, &out);
1034 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1035}
1036
Andrei Homescufc221502022-10-08 03:51:17 +00001037TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001038 if (socketType() == SocketType::TIPC) {
1039 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1040 }
1041
Andrei Homescufc221502022-10-08 03:51:17 +00001042 auto proc = createRpcTestSocketServerProcess({
1043 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1044 .serverSupportedFileDescriptorTransportModes =
1045 {RpcSession::FileDescriptorTransportMode::UNIX},
1046 });
1047
1048 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1049 ASSERT_NE(badFd, -1);
1050
1051 // Close the file descriptor so it becomes invalid for dup
1052 close(badFd);
1053
1054 Parcel p1;
1055 p1.markForBinder(proc.rootBinder);
1056 p1.writeInt32(3);
1057 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1058
1059 Parcel pRaw;
1060 pRaw.markForBinder(proc.rootBinder);
1061 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1062
1063 pRaw.setDataPosition(0);
1064 EXPECT_EQ(3, pRaw.readInt32());
1065 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1066}
1067
Andrei Homescu68a55612022-08-02 01:25:15 +00001068#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001069TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001070 if constexpr (!kEnableSharedLibs) {
1071 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1072 }
1073
Steven Moreland4313d7e2021-07-15 23:41:22 +00001074 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001075
1076 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1077 ASSERT_NE(binder, nullptr);
1078
1079 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1080}
1081
1082TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001083 if constexpr (!kEnableSharedLibs) {
1084 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1085 }
1086
Steven Moreland4313d7e2021-07-15 23:41:22 +00001087 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001088
1089 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1090 ASSERT_NE(binder, nullptr);
1091
1092 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1093 ASSERT_NE(ndkBinder, nullptr);
1094
1095 std::string out;
1096 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1097 ASSERT_TRUE(status.isOk()) << status.getDescription();
1098 ASSERT_EQ("aoeuaoeu", out);
1099}
Andrei Homescu68a55612022-08-02 01:25:15 +00001100#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001101
Steven Moreland5553ac42020-11-11 02:14:45 +00001102ssize_t countFds() {
1103 DIR* dir = opendir("/proc/self/fd/");
1104 if (dir == nullptr) return -1;
1105 ssize_t ret = 0;
1106 dirent* ent;
1107 while ((ent = readdir(dir)) != nullptr) ret++;
1108 closedir(dir);
1109 return ret;
1110}
1111
Andrei Homescua858b0e2022-08-01 23:43:09 +00001112TEST_P(BinderRpc, Fds) {
1113 if (serverSingleThreaded()) {
1114 GTEST_SKIP() << "This test requires multiple threads";
1115 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001116 if (socketType() == SocketType::TIPC) {
1117 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1118 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001119
Steven Moreland5553ac42020-11-11 02:14:45 +00001120 ssize_t beforeFds = countFds();
1121 ASSERT_GE(beforeFds, 0);
1122 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001123 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001124 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1125 }
1126 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1127}
1128
Andrei Homescud65666d2023-03-03 07:28:02 +00001129#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001130
1131static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1132 std::vector<BinderRpc::ParamType> ret;
1133
1134 for (const auto& clientVersion : testVersions()) {
1135 for (const auto& serverVersion : testVersions()) {
1136 ret.push_back(BinderRpc::ParamType{
1137 .type = SocketType::TIPC,
1138 .security = RpcSecurity::RAW,
1139 .clientVersion = clientVersion,
1140 .serverVersion = serverVersion,
1141 .singleThreaded = true,
1142 .noKernel = true,
1143 });
1144 }
1145 }
1146
1147 return ret;
1148}
1149
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001150INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1151 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001152#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001153bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001154 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001155 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001156
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001157 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001158 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001159
1160 if (errno == EAFNOSUPPORT) {
1161 return false;
1162 }
1163
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001164 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001165
1166 sockaddr_vm serverAddr{
1167 .svm_family = AF_VSOCK,
1168 .svm_port = vsockPort,
1169 .svm_cid = VMADDR_CID_ANY,
1170 };
1171 int ret = TEMP_FAILURE_RETRY(
1172 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1173 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1174 strerror(errno));
1175
1176 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1177 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1178 strerror(errno));
1179
1180 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1181 // to see if the kernel supports it. It's safe to use a blocking
1182 // connect because vsock sockets have a 2 second connection timeout,
1183 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001184 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001185 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001186 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
Andrei Homescu992a4052022-06-28 21:26:18 +00001187 strerror(errno));
1188
1189 bool success = false;
1190 sockaddr_vm connectAddr{
1191 .svm_family = AF_VSOCK,
1192 .svm_port = vsockPort,
1193 .svm_cid = VMADDR_CID_LOCAL,
1194 };
1195 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1196 sizeof(connectAddr)));
1197 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001198 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001199 while (true) {
1200 pollfd pfd[]{
1201 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1202 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1203 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001204 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001205 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1206
1207 if (pfd[0].revents & POLLIN) {
1208 sockaddr_vm acceptAddr;
1209 socklen_t acceptAddrLen = sizeof(acceptAddr);
1210 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1211 reinterpret_cast<sockaddr*>(&acceptAddr),
1212 &acceptAddrLen, SOCK_CLOEXEC));
1213 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1214 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1215 "Truncated address");
1216
1217 // Store the fd in acceptFd so we keep the connection alive
1218 // while polling connectFd
1219 acceptFd.reset(ret);
1220 }
1221
1222 if (pfd[1].revents & POLLOUT) {
1223 // Connect either succeeded or timed out
1224 int connectErrno;
1225 socklen_t connectErrnoLen = sizeof(connectErrno);
1226 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1227 &connectErrnoLen);
1228 LOG_ALWAYS_FATAL_IF(ret == -1,
1229 "Could not getsockopt() after connect() "
1230 "on non-blocking socket: %s.",
1231 strerror(errno));
1232
1233 // We're done, this is all we wanted
1234 success = connectErrno == 0;
1235 break;
1236 }
1237 }
1238 } else {
1239 success = ret == 0;
1240 }
1241
1242 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1243
1244 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001245}
1246
Yifan Hong1deca4b2021-09-10 16:16:44 -07001247static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001248 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1249 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001250
1251 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001252
Steven Moreland9f250b02023-05-16 23:27:42 +00001253#ifdef __BIONIC__
1254 // Devices may not have vsock support. AVF tests will verify whether they do, but
1255 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001256 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001257#else
1258 // On host machines, we always assume we have vsock loopback. If we don't, the
1259 // subsequent failures will be more clear than showing one now.
1260 static bool hasVsockLoopback = true;
1261#endif
Steven Morelandda573042021-06-12 01:13:45 +00001262
1263 if (hasVsockLoopback) {
1264 ret.push_back(SocketType::VSOCK);
1265 }
1266
1267 return ret;
1268}
1269
Steven Morelandb469f432023-07-28 22:13:47 +00001270static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1271 std::vector<BinderRpc::ParamType> ret;
1272
Steven Morelandf7421432023-07-28 22:41:44 +00001273 constexpr bool full = false;
1274
Steven Morelandb469f432023-07-28 22:13:47 +00001275 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001276 if (full || type == SocketType::UNIX) {
1277 for (const auto& security : RpcSecurityValues()) {
1278 for (const auto& clientVersion : testVersions()) {
1279 for (const auto& serverVersion : testVersions()) {
1280 for (bool singleThreaded : {false, true}) {
1281 for (bool noKernel : {false, true}) {
1282 ret.push_back(BinderRpc::ParamType{
1283 .type = type,
1284 .security = security,
1285 .clientVersion = clientVersion,
1286 .serverVersion = serverVersion,
1287 .singleThreaded = singleThreaded,
1288 .noKernel = noKernel,
1289 });
1290 }
Steven Morelandb469f432023-07-28 22:13:47 +00001291 }
1292 }
1293 }
1294 }
Steven Morelandf7421432023-07-28 22:41:44 +00001295 } else {
1296 ret.push_back(BinderRpc::ParamType{
1297 .type = type,
1298 .security = RpcSecurity::RAW,
1299 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1300 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1301 .singleThreaded = false,
1302 .noKernel = false,
1303 });
Steven Morelandb469f432023-07-28 22:13:47 +00001304 }
1305 }
Steven Morelandf7421432023-07-28 22:41:44 +00001306
Steven Morelandb469f432023-07-28 22:13:47 +00001307 return ret;
1308}
1309
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001310INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1311 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001312
Yifan Hong702115c2021-06-24 15:39:18 -07001313class BinderRpcServerRootObject
1314 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001315
1316TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1317 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1318 auto setRootObject = [](bool isStrong) -> SetFn {
1319 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1320 };
1321
Yifan Hong702115c2021-06-24 15:39:18 -07001322 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001323 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001324 auto binder1 = sp<BBinder>::make();
1325 IBinder* binderRaw1 = binder1.get();
1326 setRootObject(isStrong1)(server.get(), binder1);
1327 EXPECT_EQ(binderRaw1, server->getRootObject());
1328 binder1.clear();
1329 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1330
1331 auto binder2 = sp<BBinder>::make();
1332 IBinder* binderRaw2 = binder2.get();
1333 setRootObject(isStrong2)(server.get(), binder2);
1334 EXPECT_EQ(binderRaw2, server->getRootObject());
1335 binder2.clear();
1336 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1337}
1338
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001339INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1340 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1341 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001342
Yifan Hong1a235852021-05-13 16:07:47 -07001343class OneOffSignal {
1344public:
1345 // If notify() was previously called, or is called within |duration|, return true; else false.
1346 template <typename R, typename P>
1347 bool wait(std::chrono::duration<R, P> duration) {
1348 std::unique_lock<std::mutex> lock(mMutex);
1349 return mCv.wait_for(lock, duration, [this] { return mValue; });
1350 }
1351 void notify() {
1352 std::unique_lock<std::mutex> lock(mMutex);
1353 mValue = true;
1354 lock.unlock();
1355 mCv.notify_all();
1356 }
1357
1358private:
1359 std::mutex mMutex;
1360 std::condition_variable mCv;
1361 bool mValue = false;
1362};
1363
Yifan Hong194acf22021-06-29 18:44:56 -07001364TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001365 bool expectDebuggable = false;
1366#if defined(__ANDROID__)
1367 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1368 android::base::GetProperty("ro.build.type", "") != "user";
1369#else
Yifan Hong194acf22021-06-29 18:44:56 -07001370 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1371 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1372 "to binderHostDeviceTest. Hence, just disable this test on host.";
1373#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001374 if constexpr (!kEnableKernelIpc) {
1375 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1376 "at build time.";
1377 }
1378
Yifan Hong194acf22021-06-29 18:44:56 -07001379 sp<IServiceManager> sm = defaultServiceManager();
1380 ASSERT_NE(nullptr, sm);
1381 // Any Java service with non-empty getInterfaceDescriptor() would do.
1382 // Let's pick batteryproperties.
1383 auto binder = sm->checkService(String16("batteryproperties"));
1384 ASSERT_NE(nullptr, binder);
1385 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001386 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001387 ASSERT_EQ(OK, binder->pingBinder());
1388
1389 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001390 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001391 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001392 auto socket = rpcServer->releaseServer();
1393
1394 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001395 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1396
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001397 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001398 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001399 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1400 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001401 << statusToString(setRpcClientDebugStatus);
1402 GTEST_SKIP();
1403 }
1404
1405 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001406
1407 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001408 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001409 auto rpcBinder = rpcSession->getRootObject();
1410 ASSERT_NE(nullptr, rpcBinder);
1411
1412 ASSERT_EQ(OK, rpcBinder->pingBinder());
1413
1414 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1415 << "getInterfaceDescriptor should not crash system_server";
1416 ASSERT_EQ(OK, rpcBinder->pingBinder());
1417}
1418
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001419class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1420public:
1421 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001422 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001423 std::to_string(std::get<1>(info.param));
1424 }
1425};
1426
1427TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001428 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001429 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001430 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001431 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001432 ASSERT_FALSE(server->hasServer());
1433 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1434 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001435 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001436 ASSERT_FALSE(server->hasServer());
1437 ASSERT_EQ(sinkFd, retrieved.get());
1438}
1439
1440TEST_P(BinderRpcServerOnly, Shutdown) {
1441 if constexpr (!kEnableRpcThreads) {
1442 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1443 }
1444
1445 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001446 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001447 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001448 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1449 auto joinEnds = std::make_shared<OneOffSignal>();
1450
1451 // If things are broken and the thread never stops, don't block other tests. Because the thread
1452 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1453 // shared pointers are passed.
1454 std::thread([server, joinEnds] {
1455 server->join();
1456 joinEnds->notify();
1457 }).detach();
1458
1459 bool shutdown = false;
1460 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001461 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001462 if (server->shutdown()) shutdown = true;
1463 }
1464 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1465
1466 ASSERT_TRUE(joinEnds->wait(2s))
1467 << "After server->shutdown() returns true, join() did not stop after 2s";
1468}
1469
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001470INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1471 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1472 ::testing::ValuesIn(testVersions())),
1473 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001474
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001475class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001476public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001477 // Only parameterized only server version because `RpcSession` is bypassed
1478 // in the client half of the tests.
1479 using Param =
1480 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001481 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001482
1483 // A server that handles client socket connections.
1484 class Server {
1485 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001486 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001487
Yifan Hong1deca4b2021-09-10 16:16:44 -07001488 explicit Server() {}
1489 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001490 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001491 [[nodiscard]] AssertionResult setUp(
1492 const Param& param,
1493 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001494 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001495 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001496 if (!rpcServer->setProtocolVersion(serverVersion)) {
1497 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1498 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001499 switch (socketType) {
1500 case SocketType::PRECONNECTED: {
1501 return AssertionFailure() << "Not supported by this test";
1502 } break;
1503 case SocketType::UNIX: {
1504 auto addr = allocateSocketAddress();
1505 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1506 if (status != OK) {
1507 return AssertionFailure()
1508 << "setupUnixDomainServer: " << statusToString(status);
1509 }
1510 mConnectToServer = [addr] {
1511 return connectTo(UnixSocketAddress(addr.c_str()));
1512 };
1513 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001514 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001515 unique_fd bootstrapFdClient, bootstrapFdServer;
1516 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001517 return AssertionFailure() << "Socketpair() failed";
1518 }
1519 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1520 std::move(bootstrapFdServer));
1521 if (status != OK) {
1522 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1523 << statusToString(status);
1524 }
1525 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1526 mAcceptConnection = &Server::recvmsgServerConnection;
1527 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1528 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001529 case SocketType::UNIX_RAW: {
1530 auto addr = allocateSocketAddress();
1531 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1532 if (status != OK) {
1533 return AssertionFailure()
1534 << "setupRawSocketServer: " << statusToString(status);
1535 }
1536 mConnectToServer = [addr] {
1537 return connectTo(UnixSocketAddress(addr.c_str()));
1538 };
1539 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001540 case SocketType::VSOCK: {
1541 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001542 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001543 if (status != OK) {
1544 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1545 }
1546 mConnectToServer = [port] {
1547 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1548 };
1549 } break;
1550 case SocketType::INET: {
1551 unsigned int port;
1552 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1553 if (status != OK) {
1554 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1555 }
1556 mConnectToServer = [port] {
1557 const char* addr = kLocalInetAddress;
1558 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001559 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001560 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1561 auto fd = connectTo(
1562 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1563 if (fd.ok()) return fd;
1564 }
1565 ALOGE("None of the socket address resolved for %s:%u can be connected",
1566 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001567 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001568 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001569 } break;
1570 case SocketType::TIPC: {
1571 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1572 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001573 }
1574 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001575 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001576 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001577 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1578 mSetup = true;
1579 return AssertionSuccess();
1580 }
1581 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1582 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1583 return mCertVerifier;
1584 }
1585 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1586 void start() {
1587 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1588 mThread = std::make_unique<std::thread>(&Server::run, this);
1589 }
David Brazdil21c887c2022-09-23 12:25:18 +01001590
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001591 unique_fd acceptServerConnection() {
1592 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001593 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1594 }
1595
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001596 unique_fd recvmsgServerConnection() {
1597 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001598 int buf;
1599 iovec iov{&buf, sizeof(buf)};
1600
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001601 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001602 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001603 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001604 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1605 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001606 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001607 }
1608
Yifan Hong1deca4b2021-09-10 16:16:44 -07001609 void run() {
1610 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1611
1612 std::vector<std::thread> threads;
1613 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001614 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001615 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1616 }
1617
1618 for (auto& thread : threads) thread.join();
1619 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001620 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001622 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001623 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001624 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001625 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001626 }
Yifan Honge07d2732021-09-13 21:59:14 -07001627 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001628 shutdown();
1629 join();
1630 }
1631 void shutdown() { mFdTrigger->trigger(); }
1632
1633 void setPostConnect(
1634 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1635 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001636 }
1637
1638 private:
1639 std::unique_ptr<std::thread> mThread;
1640 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001641 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001643 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001644 std::unique_ptr<RpcTransportCtx> mCtx;
1645 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1646 std::make_shared<RpcCertificateVerifierSimple>();
1647 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001648 // The function invoked after connection and handshake. By default, it is
1649 // |defaultPostConnect| that sends |kMessage| to the client.
1650 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1651 Server::defaultPostConnect;
1652
1653 void join() {
1654 if (mThread != nullptr) {
1655 mThread->join();
1656 mThread = nullptr;
1657 }
1658 }
1659
1660 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1661 FdTrigger* fdTrigger) {
1662 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001663 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001664 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001665 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001666 if (status != OK) return AssertionFailure() << statusToString(status);
1667 return AssertionSuccess();
1668 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001669 };
1670
1671 class Client {
1672 public:
1673 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1674 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001675 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001676 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1677 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001678 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001679 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001680 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1681 return AssertionSuccess();
1682 }
1683 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1684 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1685 return mCertVerifier;
1686 }
Yifan Hong67519322021-09-13 18:51:16 -07001687 // connect() and do handshake
1688 bool setUpTransport() {
1689 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001690 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001691 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1692 return mClientTransport != nullptr;
1693 }
1694 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1695 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1696 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001697 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001698 status_t readStatus =
1699 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001700 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001701 if (readStatus != OK) {
1702 return AssertionFailure() << statusToString(readStatus);
1703 }
1704 if (readMessage != expectedMessage) {
1705 return AssertionFailure()
1706 << "Expected " << expectedMessage << ", actual " << readMessage;
1707 }
1708 return AssertionSuccess();
1709 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001710 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001711 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001712 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1713 return;
1714 }
1715 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001716 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001717 }
1718
Pawan49d74cb2022-08-03 21:19:11 +00001719 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1720
Yifan Hong1deca4b2021-09-10 16:16:44 -07001721 private:
1722 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001723 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1725 std::unique_ptr<RpcTransportCtx> mCtx;
1726 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1727 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001728 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001729 };
1730
1731 // Make A trust B.
1732 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001733 static status_t trust(RpcSecurity rpcSecurity,
1734 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1735 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001737 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1738 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1739 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001740 }
1741
1742 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001743};
1744
1745class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1746public:
1747 using Server = RpcTransportTestUtils::Server;
1748 using Client = RpcTransportTestUtils::Client;
1749 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001750 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001751 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001752 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001753 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001754 return ret;
1755 }
1756 static std::vector<ParamType> getRpcTranportTestParams() {
1757 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001758 for (auto serverVersion : testVersions()) {
1759 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1760 for (auto rpcSecurity : RpcSecurityValues()) {
1761 switch (rpcSecurity) {
1762 case RpcSecurity::RAW: {
1763 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1764 } break;
1765 case RpcSecurity::TLS: {
1766 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1767 serverVersion);
1768 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1769 serverVersion);
1770 } break;
1771 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001772 }
1773 }
1774 }
1775 return ret;
1776 }
1777 template <typename A, typename B>
1778 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001779 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1780 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001781 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1782 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001783 void SetUp() override {
1784 if constexpr (!kEnableRpcThreads) {
1785 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1786 }
1787 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788};
1789
1790TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001791 auto server = std::make_unique<Server>();
1792 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001793
1794 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001795 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001796
1797 ASSERT_EQ(OK, trust(&client, server));
1798 ASSERT_EQ(OK, trust(server, &client));
1799
1800 server->start();
1801 client.run();
1802}
1803
1804TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001805 auto server = std::make_unique<Server>();
1806 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001807
1808 std::vector<Client> clients;
1809 for (int i = 0; i < 2; i++) {
1810 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001811 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001812 ASSERT_EQ(OK, trust(&client, server));
1813 ASSERT_EQ(OK, trust(server, &client));
1814 }
1815
1816 server->start();
1817 for (auto& client : clients) client.run();
1818}
1819
1820TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001821 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1822 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001823
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001824 auto untrustedServer = std::make_unique<Server>();
1825 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001826
1827 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001828 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829
1830 ASSERT_EQ(OK, trust(untrustedServer, &client));
1831
1832 untrustedServer->start();
1833
1834 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1835 // the client can't verify the server's identity.
1836 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1837 client.run(handshakeOk);
1838}
1839TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001840 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1841 (void)serverVersion;
1842
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001843 auto validServer = std::make_unique<Server>();
1844 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001845
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001846 auto maliciousServer = std::make_unique<Server>();
1847 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001848
1849 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001850 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001851
1852 ASSERT_EQ(OK, trust(&client, validServer));
1853 ASSERT_EQ(OK, trust(validServer, &client));
1854 ASSERT_EQ(OK, trust(maliciousServer, &client));
1855
1856 maliciousServer->start();
1857
1858 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1859 // the client can't verify the server's identity.
1860 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1861 client.run(handshakeOk);
1862}
1863
1864TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001865 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1866 (void)serverVersion;
1867
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001868 auto server = std::make_unique<Server>();
1869 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001870
1871 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001872 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001873
1874 ASSERT_EQ(OK, trust(&client, server));
1875
1876 server->start();
1877
1878 // For TLS, Client should be able to verify server's identity, so client should see
1879 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1880 // identity and should drop the connection, so client shouldn't be able to read anything.
1881 bool readOk = rpcSecurity != RpcSecurity::TLS;
1882 client.run(true, readOk);
1883}
1884
1885TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001886 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1887 (void)serverVersion;
1888
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001889 auto server = std::make_unique<Server>();
1890 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001891
1892 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001893 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001894 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001895 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001896
1897 ASSERT_EQ(OK, trust(&validClient, server));
1898 ASSERT_EQ(OK, trust(&maliciousClient, server));
1899
1900 server->start();
1901
1902 // See UntrustedClient.
1903 bool readOk = rpcSecurity != RpcSecurity::TLS;
1904 maliciousClient.run(true, readOk);
1905}
1906
Yifan Hong67519322021-09-13 18:51:16 -07001907TEST_P(RpcTransportTest, Trigger) {
1908 std::string msg2 = ", world!";
1909 std::mutex writeMutex;
1910 std::condition_variable writeCv;
1911 bool shouldContinueWriting = false;
1912 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001913 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001914 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001915 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1916 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001917 if (status != OK) return AssertionFailure() << statusToString(status);
1918
1919 {
1920 std::unique_lock<std::mutex> lock(writeMutex);
1921 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1922 return AssertionFailure() << "write barrier not cleared in time!";
1923 }
1924 }
1925
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001926 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001927 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1928 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001929 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001930 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001931 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001932 << statusToString(status);
1933 return AssertionSuccess();
1934 };
1935
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936 auto server = std::make_unique<Server>();
1937 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001938
1939 // Set up client
1940 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001941 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001942
1943 // Exchange keys
1944 ASSERT_EQ(OK, trust(&client, server));
1945 ASSERT_EQ(OK, trust(server, &client));
1946
1947 server->setPostConnect(serverPostConnect);
1948
Yifan Hong67519322021-09-13 18:51:16 -07001949 server->start();
1950 // connect() to server and do handshake
1951 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001952 // read the first message. This ensures that server has finished handshake and start handling
1953 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001954 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001955 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1956 // write is on an FdTrigger that has been shut down.
1957 server->shutdown();
1958 // Continues server thread to write the second message.
1959 {
Yifan Hong22211f82021-09-14 12:32:25 -07001960 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001961 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001962 }
Yifan Hong22211f82021-09-14 12:32:25 -07001963 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001964 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001965 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001966 // On the client side, second read fails with DEAD_OBJECT
1967 ASSERT_FALSE(client.readMessage(msg2));
1968}
1969
Pawan49d74cb2022-08-03 21:19:11 +00001970TEST_P(RpcTransportTest, CheckWaitingForRead) {
1971 std::mutex readMutex;
1972 std::condition_variable readCv;
1973 bool shouldContinueReading = false;
1974 // Server will write data on transport once its started
1975 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1976 std::string message(RpcTransportTestUtils::kMessage);
1977 iovec messageIov{message.data(), message.size()};
1978 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1979 std::nullopt, nullptr);
1980 if (status != OK) return AssertionFailure() << statusToString(status);
1981
1982 {
1983 std::unique_lock<std::mutex> lock(readMutex);
1984 shouldContinueReading = true;
1985 lock.unlock();
1986 readCv.notify_all();
1987 }
1988 return AssertionSuccess();
1989 };
1990
1991 // Setup Server and client
1992 auto server = std::make_unique<Server>();
1993 ASSERT_TRUE(server->setUp(GetParam()));
1994
1995 Client client(server->getConnectToServerFn());
1996 ASSERT_TRUE(client.setUp(GetParam()));
1997
1998 ASSERT_EQ(OK, trust(&client, server));
1999 ASSERT_EQ(OK, trust(server, &client));
2000 server->setPostConnect(serverPostConnect);
2001
2002 server->start();
2003 ASSERT_TRUE(client.setUpTransport());
2004 {
2005 // Wait till server writes data
2006 std::unique_lock<std::mutex> lock(readMutex);
2007 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2008 }
2009
2010 // Since there is no read polling here, we will get polling count 0
2011 ASSERT_FALSE(client.isTransportWaiting());
2012 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2013 // Thread should increment polling count, read and decrement polling count
2014 // Again, polling count should be zero here
2015 ASSERT_FALSE(client.isTransportWaiting());
2016
2017 server->shutdown();
2018}
2019
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002020INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2021 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2022 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002023
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002024class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002025 : public testing::TestWithParam<
2026 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002027public:
2028 template <typename A, typename B>
2029 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002030 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2031 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002032 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2033 }
2034 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002035 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2036 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2037 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002038 };
2039};
2040
2041TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002042 if constexpr (!kEnableRpcThreads) {
2043 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2044 }
2045
Frederick Mayledc07cf82022-05-26 20:30:12 +00002046 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002047
2048 std::vector<uint8_t> pkeyData, certData;
2049 {
2050 auto pkey = makeKeyPairForSelfSignedCert();
2051 ASSERT_NE(nullptr, pkey);
2052 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2053 ASSERT_NE(nullptr, cert);
2054 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2055 certData = serializeCertificate(cert.get(), certificateFormat);
2056 }
2057
2058 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2059 auto desCert = deserializeCertificate(certData, certificateFormat);
2060 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002061 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2062 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002063
2064 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2065 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2066
2067 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2068 ASSERT_TRUE(client.setUp(utilsParam));
2069
2070 ASSERT_EQ(OK, trust(&client, server));
2071 ASSERT_EQ(OK, trust(server, &client));
2072
2073 server->start();
2074 client.run();
2075}
2076
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002077INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002078 BinderRpc, RpcTransportTlsKeyTest,
2079 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2080 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002081 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2082 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002083 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002084#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002085
Steven Morelandc1635952021-04-01 16:20:47 +00002086} // namespace android
2087
2088int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002089 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002090 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002091
Steven Moreland5553ac42020-11-11 02:14:45 +00002092 return RUN_ALL_TESTS();
2093}