blob: 5d304f4bd21f85957aac0d395c4eb9ad326a1d33 [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;
46using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070047using testing::AssertionFailure;
48using testing::AssertionResult;
49using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070050
Steven Moreland5553ac42020-11-11 02:14:45 +000051namespace android {
52
Andrei Homescu12106de2022-04-27 04:42:21 +000053#ifdef BINDER_TEST_NO_SHARED_LIBS
54constexpr bool kEnableSharedLibs = false;
55#else
56constexpr bool kEnableSharedLibs = true;
57#endif
58
Andrei Homescud65666d2023-03-03 07:28:02 +000059#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000060constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
61#endif
62
Frederick Maylea12b0962022-06-25 01:13:22 +000063static std::string WaitStatusToString(int wstatus) {
64 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000065 return std::format("exit status {}", WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000066 }
67 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000068 return std::format("term signal {}", WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000069 }
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000070 return std::format("unexpected state {}", wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000071}
72
Steven Moreland276d8df2022-09-28 23:56:39 +000073static void debugBacktrace(pid_t pid) {
74 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
75 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
76}
77
Steven Moreland5553ac42020-11-11 02:14:45 +000078class Process {
79public:
Andrei Homescu96834632022-10-14 00:49:49 +000080 Process(Process&& other)
81 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
82 mReadEnd(std::move(other.mReadEnd)),
83 mWriteEnd(std::move(other.mWriteEnd)) {
84 // The default move constructor doesn't clear mPid after moving it,
85 // which we need to do because the destructor checks for mPid!=0
86 mPid = other.mPid;
87 other.mPid = 0;
88 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070089 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
90 unique_fd childWriteEnd;
91 unique_fd childReadEnd;
92 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
93 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +000094 if (0 == (mPid = fork())) {
95 // racey: assume parent doesn't crash before this is set
96 prctl(PR_SET_PDEATHSIG, SIGHUP);
97
Yifan Hong1deca4b2021-09-10 16:16:44 -070098 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000099
100 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000101 }
102 }
103 ~Process() {
104 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000105 int wstatus;
106 waitpid(mPid, &wstatus, 0);
107 if (mCustomExitStatusCheck) {
108 mCustomExitStatusCheck(wstatus);
109 } else {
110 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
111 << "server process failed: " << WaitStatusToString(wstatus);
112 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000113 }
114 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700115 borrowed_fd readEnd() { return mReadEnd; }
116 borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000117
Frederick Maylea12b0962022-06-25 01:13:22 +0000118 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
119 mCustomExitStatusCheck = std::move(f);
120 }
121
Frederick Mayle69a0c992022-05-26 20:38:39 +0000122 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
123 void terminate() { kill(mPid, SIGTERM); }
124
Steven Moreland276d8df2022-09-28 23:56:39 +0000125 pid_t getPid() { return mPid; }
126
Steven Moreland5553ac42020-11-11 02:14:45 +0000127private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000128 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000129 pid_t mPid = 0;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700130 unique_fd mReadEnd;
131 unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000132};
133
134static std::string allocateSocketAddress() {
135 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000136 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000137 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700138 unlink(ret.c_str());
139 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000140};
141
Steven Morelandda573042021-06-12 01:13:45 +0000142static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000143 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000144 return vsockPort++;
145}
146
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700147static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000148 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700149 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700150 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
151 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
152 PLOGF("initUnixSocket failed to bind");
153 }
Alice Wang893a9912022-10-24 10:44:09 +0000154 return fd;
155}
156
Andrei Homescu96834632022-10-14 00:49:49 +0000157// Destructors need to be defined, even if pure virtual
158ProcessSession::~ProcessSession() {}
159
160class LinuxProcessSession : public ProcessSession {
161public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000162 // reference to process hosting a socket server
163 Process host;
164
Andrei Homescu96834632022-10-14 00:49:49 +0000165 LinuxProcessSession(LinuxProcessSession&&) = default;
166 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
167 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168 for (auto& session : sessions) {
169 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000170 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000171
Steven Moreland67f85902023-03-15 01:13:49 +0000172 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
173 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000175
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000176 EXPECT_NE(nullptr, session);
177 EXPECT_NE(nullptr, session->state());
178 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000179
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 wp<RpcSession> weakSession = session;
181 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000182
Steven Moreland57042712022-10-04 23:56:45 +0000183 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
184 // the object should not actually be promotable. By looping, we distinguish a race here
185 // from a bug causing the object to not be promotable.
186 for (size_t i = 0; i < 3; i++) {
187 sp<RpcSession> strongSession = weakSession.promote();
188 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000189 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000190 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
191 "Leaked sess: ")
192 << strongSession->getStrongCount() << " checked time " << i;
193
194 if (strongSession != nullptr) {
195 sleep(1);
196 }
197 }
Steven Moreland736664b2021-05-01 04:27:25 +0000198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000200
Andrei Homescu96834632022-10-14 00:49:49 +0000201 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
202 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000203 }
Andrei Homescu96834632022-10-14 00:49:49 +0000204
205 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000206};
207
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700208static unique_fd connectTo(const RpcSocketAddress& addr) {
209 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700210 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700211 if (!serverFd.ok()) {
212 PLOGF("Could not create socket %s", addr.toString().c_str());
213 }
Steven Moreland4198a122021-08-03 17:37:58 -0700214
215 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700216 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700217 }
218 return serverFd;
219}
220
Andrei Homescud65666d2023-03-03 07:28:02 +0000221#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700222static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
223 unique_fd sockClient, sockServer;
224 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700225 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100226 }
227
228 int zero = 0;
229 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700230 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100231 fds.emplace_back(std::move(sockServer));
232
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000233 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700234 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100235 }
236 return std::move(sockClient);
237}
Andrei Homescud65666d2023-03-03 07:28:02 +0000238#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100239
Andrei Homescuf30148c2023-03-10 00:31:45 +0000240std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
241 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000242}
Andrei Homescu2a298012022-06-15 01:08:54 +0000243
Andrei Homescu96834632022-10-14 00:49:49 +0000244// This creates a new process serving an interface on a certain number of
245// threads.
246std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
247 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700248 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000249
Steven Moreland67f85902023-03-15 01:13:49 +0000250 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700251 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
252 "%s: %zu != %zu", __func__,
253 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000254 }
255
Steven Morelandb469f432023-07-28 22:13:47 +0000256 SocketType socketType = GetParam().type;
257 RpcSecurity rpcSecurity = GetParam().security;
258 uint32_t clientVersion = GetParam().clientVersion;
259 uint32_t serverVersion = GetParam().serverVersion;
260 bool singleThreaded = GetParam().singleThreaded;
261 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000262
263 std::string path = android::base::GetExecutableDirectory();
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000264 auto servicePath =
265 std::format("{}/binder_rpc_test_service{}{}", path,
266 singleThreaded ? "_single_threaded" : "", noKernel ? "_no_kernel" : "");
Andrei Homescu96834632022-10-14 00:49:49 +0000267
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700268 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000269
Alice Wang893a9912022-10-24 10:44:09 +0000270 auto addr = allocateSocketAddress();
271 // Initializes the socket before the fork/exec.
272 if (socketType == SocketType::UNIX_RAW) {
273 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000274 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
275 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
276 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700277 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700278 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000279 }
Alice Wang893a9912022-10-24 10:44:09 +0000280 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000281
Andrei Homescu96834632022-10-14 00:49:49 +0000282 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700283 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000284 if (socketType == SocketType::TIPC) {
285 // Trusty has a single persistent service
286 return;
287 }
288
Andrei Homescu96834632022-10-14 00:49:49 +0000289 auto writeFd = std::to_string(writeEnd.get());
290 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800291 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
292 readFd.c_str(), NULL);
293 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
294 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000295 }));
296
297 BinderRpcTestServerConfig serverConfig;
298 serverConfig.numThreads = options.numThreads;
299 serverConfig.socketType = static_cast<int32_t>(socketType);
300 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
301 serverConfig.serverVersion = serverVersion;
302 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000303 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000304 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000305 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
306 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
307 static_cast<int32_t>(mode));
308 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000309 if (socketType != SocketType::TIPC) {
310 writeToFd(ret->host.writeEnd(), serverConfig);
311 }
Andrei Homescu96834632022-10-14 00:49:49 +0000312
313 std::vector<sp<RpcSession>> sessions;
314 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
315 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000316 std::unique_ptr<RpcTransportCtxFactory> factory;
317 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000318#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000319 factory = RpcTransportCtxFactoryTipcAndroid::make();
320#else
321 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
322#endif
323 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000324 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000325 }
326 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100327 }
328
Andrei Homescu68a55612022-08-02 01:25:15 +0000329 BinderRpcTestServerInfo serverInfo;
330 if (socketType != SocketType::TIPC) {
331 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
332 BinderRpcTestClientInfo clientInfo;
333 for (const auto& session : sessions) {
334 auto& parcelableCert = clientInfo.certs.emplace_back();
335 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
336 }
337 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000338
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700339 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000340 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700341 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000342 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000343
Andrei Homescu68a55612022-08-02 01:25:15 +0000344 if (rpcSecurity == RpcSecurity::TLS) {
345 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700346 LOG_ALWAYS_FATAL_IF(
347 OK !=
348 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000349 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700350 }
351
Andrei Homescu96834632022-10-14 00:49:49 +0000352 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000353
Steven Moreland67f85902023-03-15 01:13:49 +0000354 for (size_t i = 0; i < sessions.size(); i++) {
355 const auto& session = sessions.at(i);
356
357 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
358 ? options.numIncomingConnectionsBySession.at(i)
359 : 0;
360
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700361 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000362 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000363 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000364 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000365
Andrei Homescu96834632022-10-14 00:49:49 +0000366 switch (socketType) {
367 case SocketType::PRECONNECTED:
368 status = session->setupPreconnectedClient({}, [=]() {
369 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
370 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000371 break;
Alice Wang893a9912022-10-24 10:44:09 +0000372 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000373 case SocketType::UNIX:
374 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
375 break;
376 case SocketType::UNIX_BOOTSTRAP:
377 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700378 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000379 break;
380 case SocketType::VSOCK:
381 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
382 break;
383 case SocketType::INET:
384 status = session->setupInetClient("127.0.0.1", serverInfo.port);
385 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000386 case SocketType::TIPC:
387 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000388#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000389 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000390 for (size_t i = 0; i < 5; i++) {
391 // Try to connect several times,
392 // in case the service is slow to start
393 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
394 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700395 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000396 }
397 usleep(50000);
398 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700399 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000400#else
401 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700402 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000403#endif
404 });
405 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000406 default:
407 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000408 }
Andrei Homescu96834632022-10-14 00:49:49 +0000409 if (options.allowConnectFailure && status != OK) {
410 ret->sessions.clear();
411 break;
412 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700413 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Andrei Homescu96834632022-10-14 00:49:49 +0000414 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000415 }
Andrei Homescu96834632022-10-14 00:49:49 +0000416 return ret;
417}
Steven Morelandc1635952021-04-01 16:20:47 +0000418
Andrei Homescua858b0e2022-08-01 23:43:09 +0000419TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
420 if (clientOrServerSingleThreaded()) {
421 GTEST_SKIP() << "This test requires multiple threads";
422 }
423
Steven Moreland5553ac42020-11-11 02:14:45 +0000424 constexpr size_t kNumThreads = 10;
425
Steven Moreland4313d7e2021-07-15 23:41:22 +0000426 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000427
428 EXPECT_OK(proc.rootIface->lock());
429
430 // block all but one thread taking locks
431 std::vector<std::thread> ts;
432 for (size_t i = 0; i < kNumThreads - 1; i++) {
433 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
434 }
435
Steven Morelandd6d816f2022-12-23 01:37:17 +0000436 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000437
438 // other calls still work
439 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
440
Steven Morelandd6d816f2022-12-23 01:37:17 +0000441 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000442 size_t epochMsBefore = epochMillis();
443 // after this, we should never see a response within this time
444 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
445
446 // this call should be blocked for blockTimeMs
447 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
448
449 size_t epochMsAfter = epochMillis();
450 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
451
452 for (auto& t : ts) t.join();
453}
454
Steven Moreland27f620a2023-03-06 19:44:36 +0000455static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000456 size_t epochMsBefore = epochMillis();
457
458 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700459 for (size_t i = 0; i < numCalls; i++) {
460 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000461 }
462
463 for (auto& t : ts) t.join();
464
465 size_t epochMsAfter = epochMillis();
466
Yifan Hong1f44f982021-10-08 17:16:47 -0700467 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000468
Steven Moreland9c203222023-05-31 21:26:41 +0000469 // Potential flake, but make sure calls are handled in parallel. Due
470 // to past flakes, this only checks that the amount of time taken has
471 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
472 // check this more exactly.
473 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700474}
475
Andrei Homescua858b0e2022-08-01 23:43:09 +0000476TEST_P(BinderRpc, ThreadPoolOverSaturated) {
477 if (clientOrServerSingleThreaded()) {
478 GTEST_SKIP() << "This test requires multiple threads";
479 }
480
Yifan Hong1f44f982021-10-08 17:16:47 -0700481 constexpr size_t kNumThreads = 10;
482 constexpr size_t kNumCalls = kNumThreads + 3;
483 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000484
485 // b/272429574 - below 500ms, the test fails
486 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700487}
488
Andrei Homescua858b0e2022-08-01 23:43:09 +0000489TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
490 if (clientOrServerSingleThreaded()) {
491 GTEST_SKIP() << "This test requires multiple threads";
492 }
493
Yifan Hong1f44f982021-10-08 17:16:47 -0700494 constexpr size_t kNumThreads = 20;
495 constexpr size_t kNumOutgoingConnections = 10;
496 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
497 auto proc = createRpcTestSocketServerProcess(
498 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000499
500 // b/272429574 - below 500ms, the test fails
501 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000502}
503
Andrei Homescua858b0e2022-08-01 23:43:09 +0000504TEST_P(BinderRpc, ThreadingStressTest) {
505 if (clientOrServerSingleThreaded()) {
506 GTEST_SKIP() << "This test requires multiple threads";
507 }
508
Steven Moreland27f620a2023-03-06 19:44:36 +0000509 constexpr size_t kNumClientThreads = 5;
510 constexpr size_t kNumServerThreads = 5;
511 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000512
Steven Moreland4313d7e2021-07-15 23:41:22 +0000513 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000514
515 std::vector<std::thread> threads;
516 for (size_t i = 0; i < kNumClientThreads; i++) {
517 threads.push_back(std::thread([&] {
518 for (size_t j = 0; j < kNumCalls; j++) {
519 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000520 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 EXPECT_EQ(proc.rootBinder, out);
522 }
523 }));
524 }
525
526 for (auto& t : threads) t.join();
527}
528
Steven Moreland925ba0a2021-09-17 18:06:32 -0700529static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
530 std::vector<std::thread> threads;
531 for (size_t i = 0; i < threadCount; i++) {
532 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
533 }
534 for (auto& t : threads) t.join();
535}
536
Andrei Homescua858b0e2022-08-01 23:43:09 +0000537TEST_P(BinderRpc, OnewayStressTest) {
538 if (clientOrServerSingleThreaded()) {
539 GTEST_SKIP() << "This test requires multiple threads";
540 }
541
Steven Morelandc6046982021-04-20 00:49:42 +0000542 constexpr size_t kNumClientThreads = 10;
543 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700544 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000545
Steven Moreland4313d7e2021-07-15 23:41:22 +0000546 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000547
548 std::vector<std::thread> threads;
549 for (size_t i = 0; i < kNumClientThreads; i++) {
550 threads.push_back(std::thread([&] {
551 for (size_t j = 0; j < kNumCalls; j++) {
552 EXPECT_OK(proc.rootIface->sendString("a"));
553 }
Steven Morelandc6046982021-04-20 00:49:42 +0000554 }));
555 }
556
557 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700558
559 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000560}
561
Frederick Mayleb0221d12022-10-03 23:10:53 +0000562TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
563 if (!supportsFdTransport()) {
564 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
565 }
566 if (clientOrServerSingleThreaded()) {
567 GTEST_SKIP() << "This test requires multiple threads";
568 }
569
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000570 constexpr size_t kNumServerThreads = 3;
571
Frederick Mayleb0221d12022-10-03 23:10:53 +0000572 // This test forces a oneway transaction to be queued by issuing two
573 // `blockingSendFdOneway` calls, then drains the queue by issuing two
574 // `blockingRecvFd` calls.
575 //
576 // For more details about the queuing semantics see
577 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
578
579 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000580 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000581 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
582 .serverSupportedFileDescriptorTransportModes =
583 {RpcSession::FileDescriptorTransportMode::UNIX},
584 });
585
586 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
587 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
588 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
589 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
590
591 android::os::ParcelFileDescriptor fdA;
592 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
593 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700594 ASSERT_TRUE(android::base::ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000595 EXPECT_EQ(result, "a");
596
597 android::os::ParcelFileDescriptor fdB;
598 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700599 ASSERT_TRUE(android::base::ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000600 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000601
602 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000603}
604
Andrei Homescua858b0e2022-08-01 23:43:09 +0000605TEST_P(BinderRpc, OnewayCallQueueing) {
606 if (clientOrServerSingleThreaded()) {
607 GTEST_SKIP() << "This test requires multiple threads";
608 }
609
Frederick Mayle96872592023-03-07 14:56:15 -0800610 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000611 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000612
613 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000614 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000615
Frederick Mayle96872592023-03-07 14:56:15 -0800616 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700617 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800618 for (size_t i = 0; i + 1 < kNumQueued; i++) {
619 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000620 }
Frederick Mayle96872592023-03-07 14:56:15 -0800621 for (size_t i = 0; i + 1 < kNumQueued; i++) {
622 int n;
623 proc.rootIface->blockingRecvInt(&n);
624 EXPECT_EQ(n, i);
625 }
Steven Morelandf5174272021-05-25 00:39:28 +0000626
Steven Moreland925ba0a2021-09-17 18:06:32 -0700627 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000628}
629
Andrei Homescua858b0e2022-08-01 23:43:09 +0000630TEST_P(BinderRpc, OnewayCallExhaustion) {
631 if (clientOrServerSingleThreaded()) {
632 GTEST_SKIP() << "This test requires multiple threads";
633 }
634
Steven Morelandd45be622021-06-04 02:19:37 +0000635 constexpr size_t kNumClients = 2;
636 constexpr size_t kTooLongMs = 1000;
637
Steven Moreland4313d7e2021-07-15 23:41:22 +0000638 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000639
640 // Build up oneway calls on the second session to make sure it terminates
641 // and shuts down. The first session should be unaffected (proc destructor
642 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000643 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000644
645 std::vector<std::thread> threads;
646 for (size_t i = 0; i < kNumClients; i++) {
647 // one of these threads will get stuck queueing a transaction once the
648 // socket fills up, the other will be able to fill up transactions on
649 // this object
650 threads.push_back(std::thread([&] {
651 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
652 }
653 }));
654 }
655 for (auto& t : threads) t.join();
656
657 Status status = iface->sleepMsAsync(kTooLongMs);
658 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
659
Steven Moreland798e0d12021-07-14 23:19:25 +0000660 // now that it has died, wait for the remote session to shutdown
661 std::vector<int32_t> remoteCounts;
662 do {
663 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
664 } while (remoteCounts.size() == kNumClients);
665
Steven Morelandd45be622021-06-04 02:19:37 +0000666 // the second session should be shutdown in the other process by the time we
667 // are able to join above (it'll only be hung up once it finishes processing
668 // any pending commands). We need to erase this session from the record
669 // here, so that the destructor for our session won't check that this
670 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000671 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000672}
673
Steven Moreland67f85902023-03-15 01:13:49 +0000674TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
675 if (clientOrServerSingleThreaded()) {
676 GTEST_SKIP() << "This test requires multiple threads";
677 }
678
679 // session 0 - will check for leaks in destrutor of proc
680 // session 1 - we want to make sure it gets deleted when we drop all references to it
681 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700682 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000683
684 wp<RpcSession> session = proc.proc->sessions.at(1).session;
685
686 // remove all references to the second session
687 proc.proc->sessions.at(1).root = nullptr;
688 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
689
690 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
691 // to drain commands.
692 for (size_t i = 0; i < 100; i++) {
693 usleep(10 * 1000);
694 if (session.promote() == nullptr) break;
695 }
696
697 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000698
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000699 // now that it has died, wait for the remote session to shutdown
700 std::vector<int32_t> remoteCounts;
701 do {
702 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
703 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000704}
705
Devin Moore66d5b7a2022-07-07 21:42:10 +0000706TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000707 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000708 GTEST_SKIP() << "This test requires multiple threads";
709 }
710 class MyDeathRec : public IBinder::DeathRecipient {
711 public:
712 void binderDied(const wp<IBinder>& /* who */) override {
713 dead = true;
714 mCv.notify_one();
715 }
716 std::mutex mMtx;
717 std::condition_variable mCv;
718 bool dead = false;
719 };
720
721 // Death recipient needs to have an incoming connection to be called
722 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000723 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000724
725 auto dr = sp<MyDeathRec>::make();
726 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
727
728 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
729 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
730 }
731
732 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000733 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000734
735 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000736 // can't do this before checking the death recipient by calling
737 // forceShutdown earlier, because shutdownAndWait will also trigger
738 // a death recipient, but if we had a way to wait for the service
739 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000740 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000741 proc.expectAlreadyShutdown = true;
742}
743
744TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000745 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000746 GTEST_SKIP() << "This test requires multiple threads";
747 }
748 class MyDeathRec : public IBinder::DeathRecipient {
749 public:
750 void binderDied(const wp<IBinder>& /* who */) override {
751 dead = true;
752 mCv.notify_one();
753 }
754 std::mutex mMtx;
755 std::condition_variable mCv;
756 bool dead = false;
757 };
758
759 // Death recipient needs to have an incoming connection to be called
760 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000761 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000762
763 auto dr = sp<MyDeathRec>::make();
764 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
765
766 // Explicitly calling shutDownAndWait will cause the death recipients
767 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000768 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000769
770 std::unique_lock<std::mutex> lock(dr->mMtx);
771 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000772 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000773 }
774 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
775
Andrei Homescu96834632022-10-14 00:49:49 +0000776 proc.proc->terminate();
777 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000778 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
779 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
780 });
781 proc.expectAlreadyShutdown = true;
782}
783
Steven Moreland5ec743f2023-01-18 01:02:06 +0000784TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000785 if (socketType() == SocketType::TIPC) {
786 // This should work, but Trusty takes too long to restart the service
787 GTEST_SKIP() << "Service death test not supported on Trusty";
788 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000789 class MyDeathRec : public IBinder::DeathRecipient {
790 public:
791 void binderDied(const wp<IBinder>& /* who */) override {}
792 };
793
Steven Moreland67f85902023-03-15 01:13:49 +0000794 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000795
796 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000797 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000798}
799
800TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000801 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000802 GTEST_SKIP() << "This test requires multiple threads";
803 }
804 class MyDeathRec : public IBinder::DeathRecipient {
805 public:
806 void binderDied(const wp<IBinder>& /* who */) override {
807 GTEST_FAIL() << "This should not be called after unlinkToDeath";
808 }
809 };
810
811 // Death recipient needs to have an incoming connection to be called
812 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000813 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000814
815 auto dr = sp<MyDeathRec>::make();
816 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
817 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
818
Steven Moreland67f85902023-03-15 01:13:49 +0000819 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000820}
821
Steven Morelandc1635952021-04-01 16:20:47 +0000822TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000823 if (socketType() == SocketType::TIPC) {
824 // This should work, but Trusty takes too long to restart the service
825 GTEST_SKIP() << "Service death test not supported on Trusty";
826 }
827
Steven Moreland5553ac42020-11-11 02:14:45 +0000828 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000829 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000830
831 // make sure there is some state during crash
832 // 1. we hold their binder
833 sp<IBinderRpcSession> session;
834 EXPECT_OK(proc.rootIface->openSession("happy", &session));
835 // 2. they hold our binder
836 sp<IBinder> binder = new BBinder();
837 EXPECT_OK(proc.rootIface->holdBinder(binder));
838
839 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
840 << "Do death cleanup: " << doDeathCleanup;
841
Andrei Homescu96834632022-10-14 00:49:49 +0000842 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000843 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
844 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
845 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000846 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000847 }
848}
849
Steven Morelandd7302072021-05-15 01:32:04 +0000850TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000851 // This test only works if the current process shared the internal state of
852 // ProcessState with the service across the call to fork(). Both the static
853 // libraries and libbinder.so have their own separate copies of all the
854 // globals, so the test only works when the test client and service both use
855 // libbinder.so (when using static libraries, even a client and service
856 // using the same kind of static library should have separate copies of the
857 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000858 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000859 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
860 "at build time.";
861 }
862
Steven Moreland4313d7e2021-07-15 23:41:22 +0000863 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000864
Andrei Homescu2a298012022-06-15 01:08:54 +0000865 // we can't allocate IPCThreadState so actually the first time should
866 // succeed :(
867 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000868
869 // second time! we catch the error :)
870 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
871
Andrei Homescu96834632022-10-14 00:49:49 +0000872 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000873 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
874 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
875 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000876 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000877}
878
Frederick Mayle69a0c992022-05-26 20:38:39 +0000879TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000880 if (socketType() == SocketType::TIPC) {
881 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
882 }
883
Frederick Mayle69a0c992022-05-26 20:38:39 +0000884 auto proc = createRpcTestSocketServerProcess({
885 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
886 .serverSupportedFileDescriptorTransportModes =
887 {RpcSession::FileDescriptorTransportMode::UNIX},
888 .allowConnectFailure = true,
889 });
Andrei Homescu96834632022-10-14 00:49:49 +0000890 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
891 proc.proc->terminate();
892 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000893 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
894 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
895 });
896 proc.expectAlreadyShutdown = true;
897}
898
899TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000900 if (socketType() == SocketType::TIPC) {
901 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
902 }
903
Frederick Mayle69a0c992022-05-26 20:38:39 +0000904 auto proc = createRpcTestSocketServerProcess({
905 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
906 .serverSupportedFileDescriptorTransportModes =
907 {RpcSession::FileDescriptorTransportMode::NONE},
908 .allowConnectFailure = true,
909 });
Andrei Homescu96834632022-10-14 00:49:49 +0000910 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
911 proc.proc->terminate();
912 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000913 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
914 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
915 });
916 proc.expectAlreadyShutdown = true;
917}
918
919TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000920 if (socketType() == SocketType::TIPC) {
921 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
922 }
923
Frederick Mayle69a0c992022-05-26 20:38:39 +0000924 auto proc = createRpcTestSocketServerProcess({
925 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
926 .serverSupportedFileDescriptorTransportModes =
927 {RpcSession::FileDescriptorTransportMode::NONE,
928 RpcSession::FileDescriptorTransportMode::UNIX},
929 });
930
931 android::os::ParcelFileDescriptor out;
932 auto status = proc.rootIface->echoAsFile("hello", &out);
933 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
934}
935
936TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000937 if (socketType() == SocketType::TIPC) {
938 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
939 }
940
Frederick Mayle69a0c992022-05-26 20:38:39 +0000941 auto proc = createRpcTestSocketServerProcess({
942 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
943 .serverSupportedFileDescriptorTransportModes =
944 {RpcSession::FileDescriptorTransportMode::UNIX},
945 });
946
947 android::os::ParcelFileDescriptor out;
948 auto status = proc.rootIface->echoAsFile("hello", &out);
949 if (!supportsFdTransport()) {
950 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
951 return;
952 }
953 ASSERT_TRUE(status.isOk()) << status;
954
955 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700956 ASSERT_TRUE(android::base::ReadFdToString(out.get(), &result));
957 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000958}
959
960TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000961 if (socketType() == SocketType::TIPC) {
962 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
963 }
964
Frederick Mayle69a0c992022-05-26 20:38:39 +0000965 auto proc = createRpcTestSocketServerProcess({
966 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
967 .serverSupportedFileDescriptorTransportModes =
968 {RpcSession::FileDescriptorTransportMode::UNIX},
969 });
970
971 std::vector<android::os::ParcelFileDescriptor> files;
972 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
973 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
975 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
976
977 android::os::ParcelFileDescriptor out;
978 auto status = proc.rootIface->concatFiles(files, &out);
979 if (!supportsFdTransport()) {
980 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
981 return;
982 }
983 ASSERT_TRUE(status.isOk()) << status;
984
985 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700986 EXPECT_TRUE(android::base::ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000987 EXPECT_EQ(result, "123abcd");
988}
989
990TEST_P(BinderRpc, SendMaxFiles) {
991 if (!supportsFdTransport()) {
992 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
993 }
994
995 auto proc = createRpcTestSocketServerProcess({
996 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
997 .serverSupportedFileDescriptorTransportModes =
998 {RpcSession::FileDescriptorTransportMode::UNIX},
999 });
1000
1001 std::vector<android::os::ParcelFileDescriptor> files;
1002 for (int i = 0; i < 253; i++) {
1003 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1004 }
1005
1006 android::os::ParcelFileDescriptor out;
1007 auto status = proc.rootIface->concatFiles(files, &out);
1008 ASSERT_TRUE(status.isOk()) << status;
1009
1010 std::string result;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001011 EXPECT_TRUE(android::base::ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001012 EXPECT_EQ(result, std::string(253, 'a'));
1013}
1014
1015TEST_P(BinderRpc, SendTooManyFiles) {
1016 if (!supportsFdTransport()) {
1017 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1018 }
1019
1020 auto proc = createRpcTestSocketServerProcess({
1021 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1022 .serverSupportedFileDescriptorTransportModes =
1023 {RpcSession::FileDescriptorTransportMode::UNIX},
1024 });
1025
1026 std::vector<android::os::ParcelFileDescriptor> files;
1027 for (int i = 0; i < 254; i++) {
1028 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1029 }
1030
1031 android::os::ParcelFileDescriptor out;
1032 auto status = proc.rootIface->concatFiles(files, &out);
1033 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1034}
1035
Andrei Homescufc221502022-10-08 03:51:17 +00001036TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001037 if (socketType() == SocketType::TIPC) {
1038 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1039 }
1040
Andrei Homescufc221502022-10-08 03:51:17 +00001041 auto proc = createRpcTestSocketServerProcess({
1042 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1043 .serverSupportedFileDescriptorTransportModes =
1044 {RpcSession::FileDescriptorTransportMode::UNIX},
1045 });
1046
1047 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1048 ASSERT_NE(badFd, -1);
1049
1050 // Close the file descriptor so it becomes invalid for dup
1051 close(badFd);
1052
1053 Parcel p1;
1054 p1.markForBinder(proc.rootBinder);
1055 p1.writeInt32(3);
1056 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1057
1058 Parcel pRaw;
1059 pRaw.markForBinder(proc.rootBinder);
1060 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1061
1062 pRaw.setDataPosition(0);
1063 EXPECT_EQ(3, pRaw.readInt32());
1064 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1065}
1066
Andrei Homescu68a55612022-08-02 01:25:15 +00001067#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001068TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001069 if constexpr (!kEnableSharedLibs) {
1070 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1071 }
1072
Steven Moreland4313d7e2021-07-15 23:41:22 +00001073 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001074
1075 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1076 ASSERT_NE(binder, nullptr);
1077
1078 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1079}
1080
1081TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001082 if constexpr (!kEnableSharedLibs) {
1083 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1084 }
1085
Steven Moreland4313d7e2021-07-15 23:41:22 +00001086 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001087
1088 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1089 ASSERT_NE(binder, nullptr);
1090
1091 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1092 ASSERT_NE(ndkBinder, nullptr);
1093
1094 std::string out;
1095 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1096 ASSERT_TRUE(status.isOk()) << status.getDescription();
1097 ASSERT_EQ("aoeuaoeu", out);
1098}
Andrei Homescu68a55612022-08-02 01:25:15 +00001099#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001100
Steven Moreland5553ac42020-11-11 02:14:45 +00001101ssize_t countFds() {
1102 DIR* dir = opendir("/proc/self/fd/");
1103 if (dir == nullptr) return -1;
1104 ssize_t ret = 0;
1105 dirent* ent;
1106 while ((ent = readdir(dir)) != nullptr) ret++;
1107 closedir(dir);
1108 return ret;
1109}
1110
Andrei Homescua858b0e2022-08-01 23:43:09 +00001111TEST_P(BinderRpc, Fds) {
1112 if (serverSingleThreaded()) {
1113 GTEST_SKIP() << "This test requires multiple threads";
1114 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001115 if (socketType() == SocketType::TIPC) {
1116 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1117 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001118
Steven Moreland5553ac42020-11-11 02:14:45 +00001119 ssize_t beforeFds = countFds();
1120 ASSERT_GE(beforeFds, 0);
1121 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001122 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001123 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1124 }
1125 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1126}
1127
Andrei Homescud65666d2023-03-03 07:28:02 +00001128#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001129
1130static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1131 std::vector<BinderRpc::ParamType> ret;
1132
1133 for (const auto& clientVersion : testVersions()) {
1134 for (const auto& serverVersion : testVersions()) {
1135 ret.push_back(BinderRpc::ParamType{
1136 .type = SocketType::TIPC,
1137 .security = RpcSecurity::RAW,
1138 .clientVersion = clientVersion,
1139 .serverVersion = serverVersion,
1140 .singleThreaded = true,
1141 .noKernel = true,
1142 });
1143 }
1144 }
1145
1146 return ret;
1147}
1148
1149INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
Andrei Homescud65666d2023-03-03 07:28:02 +00001150 BinderRpc::PrintParamInfo);
1151#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001152bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001153 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001154 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001155
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001156 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001157 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001158
1159 if (errno == EAFNOSUPPORT) {
1160 return false;
1161 }
1162
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001163 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001164
1165 sockaddr_vm serverAddr{
1166 .svm_family = AF_VSOCK,
1167 .svm_port = vsockPort,
1168 .svm_cid = VMADDR_CID_ANY,
1169 };
1170 int ret = TEMP_FAILURE_RETRY(
1171 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1172 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1173 strerror(errno));
1174
1175 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1176 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1177 strerror(errno));
1178
1179 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1180 // to see if the kernel supports it. It's safe to use a blocking
1181 // connect because vsock sockets have a 2 second connection timeout,
1182 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001183 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001184 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001185 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
Andrei Homescu992a4052022-06-28 21:26:18 +00001186 strerror(errno));
1187
1188 bool success = false;
1189 sockaddr_vm connectAddr{
1190 .svm_family = AF_VSOCK,
1191 .svm_port = vsockPort,
1192 .svm_cid = VMADDR_CID_LOCAL,
1193 };
1194 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1195 sizeof(connectAddr)));
1196 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001197 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001198 while (true) {
1199 pollfd pfd[]{
1200 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1201 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1202 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001203 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001204 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1205
1206 if (pfd[0].revents & POLLIN) {
1207 sockaddr_vm acceptAddr;
1208 socklen_t acceptAddrLen = sizeof(acceptAddr);
1209 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1210 reinterpret_cast<sockaddr*>(&acceptAddr),
1211 &acceptAddrLen, SOCK_CLOEXEC));
1212 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1213 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1214 "Truncated address");
1215
1216 // Store the fd in acceptFd so we keep the connection alive
1217 // while polling connectFd
1218 acceptFd.reset(ret);
1219 }
1220
1221 if (pfd[1].revents & POLLOUT) {
1222 // Connect either succeeded or timed out
1223 int connectErrno;
1224 socklen_t connectErrnoLen = sizeof(connectErrno);
1225 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1226 &connectErrnoLen);
1227 LOG_ALWAYS_FATAL_IF(ret == -1,
1228 "Could not getsockopt() after connect() "
1229 "on non-blocking socket: %s.",
1230 strerror(errno));
1231
1232 // We're done, this is all we wanted
1233 success = connectErrno == 0;
1234 break;
1235 }
1236 }
1237 } else {
1238 success = ret == 0;
1239 }
1240
1241 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1242
1243 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001244}
1245
Yifan Hong1deca4b2021-09-10 16:16:44 -07001246static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001247 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1248 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001249
1250 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001251
Steven Moreland9f250b02023-05-16 23:27:42 +00001252#ifdef __BIONIC__
1253 // Devices may not have vsock support. AVF tests will verify whether they do, but
1254 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001255 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001256#else
1257 // On host machines, we always assume we have vsock loopback. If we don't, the
1258 // subsequent failures will be more clear than showing one now.
1259 static bool hasVsockLoopback = true;
1260#endif
Steven Morelandda573042021-06-12 01:13:45 +00001261
1262 if (hasVsockLoopback) {
1263 ret.push_back(SocketType::VSOCK);
1264 }
1265
1266 return ret;
1267}
1268
Steven Morelandb469f432023-07-28 22:13:47 +00001269static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1270 std::vector<BinderRpc::ParamType> ret;
1271
Steven Morelandf7421432023-07-28 22:41:44 +00001272 constexpr bool full = false;
1273
Steven Morelandb469f432023-07-28 22:13:47 +00001274 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001275 if (full || type == SocketType::UNIX) {
1276 for (const auto& security : RpcSecurityValues()) {
1277 for (const auto& clientVersion : testVersions()) {
1278 for (const auto& serverVersion : testVersions()) {
1279 for (bool singleThreaded : {false, true}) {
1280 for (bool noKernel : {false, true}) {
1281 ret.push_back(BinderRpc::ParamType{
1282 .type = type,
1283 .security = security,
1284 .clientVersion = clientVersion,
1285 .serverVersion = serverVersion,
1286 .singleThreaded = singleThreaded,
1287 .noKernel = noKernel,
1288 });
1289 }
Steven Morelandb469f432023-07-28 22:13:47 +00001290 }
1291 }
1292 }
1293 }
Steven Morelandf7421432023-07-28 22:41:44 +00001294 } else {
1295 ret.push_back(BinderRpc::ParamType{
1296 .type = type,
1297 .security = RpcSecurity::RAW,
1298 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1299 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1300 .singleThreaded = false,
1301 .noKernel = false,
1302 });
Steven Morelandb469f432023-07-28 22:13:47 +00001303 }
1304 }
Steven Morelandf7421432023-07-28 22:41:44 +00001305
Steven Morelandb469f432023-07-28 22:13:47 +00001306 return ret;
1307}
1308
1309INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
Yifan Hong702115c2021-06-24 15:39:18 -07001310 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001311
Yifan Hong702115c2021-06-24 15:39:18 -07001312class BinderRpcServerRootObject
1313 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001314
1315TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1316 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1317 auto setRootObject = [](bool isStrong) -> SetFn {
1318 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1319 };
1320
Yifan Hong702115c2021-06-24 15:39:18 -07001321 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001322 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001323 auto binder1 = sp<BBinder>::make();
1324 IBinder* binderRaw1 = binder1.get();
1325 setRootObject(isStrong1)(server.get(), binder1);
1326 EXPECT_EQ(binderRaw1, server->getRootObject());
1327 binder1.clear();
1328 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1329
1330 auto binder2 = sp<BBinder>::make();
1331 IBinder* binderRaw2 = binder2.get();
1332 setRootObject(isStrong2)(server.get(), binder2);
1333 EXPECT_EQ(binderRaw2, server->getRootObject());
1334 binder2.clear();
1335 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1336}
1337
1338INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001339 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1340 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001341
Yifan Hong1a235852021-05-13 16:07:47 -07001342class OneOffSignal {
1343public:
1344 // If notify() was previously called, or is called within |duration|, return true; else false.
1345 template <typename R, typename P>
1346 bool wait(std::chrono::duration<R, P> duration) {
1347 std::unique_lock<std::mutex> lock(mMutex);
1348 return mCv.wait_for(lock, duration, [this] { return mValue; });
1349 }
1350 void notify() {
1351 std::unique_lock<std::mutex> lock(mMutex);
1352 mValue = true;
1353 lock.unlock();
1354 mCv.notify_all();
1355 }
1356
1357private:
1358 std::mutex mMutex;
1359 std::condition_variable mCv;
1360 bool mValue = false;
1361};
1362
Yifan Hong194acf22021-06-29 18:44:56 -07001363TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001364 bool expectDebuggable = false;
1365#if defined(__ANDROID__)
1366 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1367 android::base::GetProperty("ro.build.type", "") != "user";
1368#else
Yifan Hong194acf22021-06-29 18:44:56 -07001369 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1370 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1371 "to binderHostDeviceTest. Hence, just disable this test on host.";
1372#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001373 if constexpr (!kEnableKernelIpc) {
1374 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1375 "at build time.";
1376 }
1377
Yifan Hong194acf22021-06-29 18:44:56 -07001378 sp<IServiceManager> sm = defaultServiceManager();
1379 ASSERT_NE(nullptr, sm);
1380 // Any Java service with non-empty getInterfaceDescriptor() would do.
1381 // Let's pick batteryproperties.
1382 auto binder = sm->checkService(String16("batteryproperties"));
1383 ASSERT_NE(nullptr, binder);
1384 auto descriptor = binder->getInterfaceDescriptor();
1385 ASSERT_GE(descriptor.size(), 0);
1386 ASSERT_EQ(OK, binder->pingBinder());
1387
1388 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001389 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001390 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001391 auto socket = rpcServer->releaseServer();
1392
1393 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001394 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1395
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001396 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001397 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001398 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1399 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001400 << statusToString(setRpcClientDebugStatus);
1401 GTEST_SKIP();
1402 }
1403
1404 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001405
1406 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001407 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001408 auto rpcBinder = rpcSession->getRootObject();
1409 ASSERT_NE(nullptr, rpcBinder);
1410
1411 ASSERT_EQ(OK, rpcBinder->pingBinder());
1412
1413 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1414 << "getInterfaceDescriptor should not crash system_server";
1415 ASSERT_EQ(OK, rpcBinder->pingBinder());
1416}
1417
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001418class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1419public:
1420 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001421 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001422 std::to_string(std::get<1>(info.param));
1423 }
1424};
1425
1426TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001427 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001428 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001429 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001430 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001431 ASSERT_FALSE(server->hasServer());
1432 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1433 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001434 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001435 ASSERT_FALSE(server->hasServer());
1436 ASSERT_EQ(sinkFd, retrieved.get());
1437}
1438
1439TEST_P(BinderRpcServerOnly, Shutdown) {
1440 if constexpr (!kEnableRpcThreads) {
1441 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1442 }
1443
1444 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001445 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001446 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001447 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1448 auto joinEnds = std::make_shared<OneOffSignal>();
1449
1450 // If things are broken and the thread never stops, don't block other tests. Because the thread
1451 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1452 // shared pointers are passed.
1453 std::thread([server, joinEnds] {
1454 server->join();
1455 joinEnds->notify();
1456 }).detach();
1457
1458 bool shutdown = false;
1459 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001460 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001461 if (server->shutdown()) shutdown = true;
1462 }
1463 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1464
1465 ASSERT_TRUE(joinEnds->wait(2s))
1466 << "After server->shutdown() returns true, join() did not stop after 2s";
1467}
1468
Frederick Mayledc07cf82022-05-26 20:30:12 +00001469INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1470 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1471 ::testing::ValuesIn(testVersions())),
1472 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001473
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001474class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001475public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001476 // Only parameterized only server version because `RpcSession` is bypassed
1477 // in the client half of the tests.
1478 using Param =
1479 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001480 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001481
1482 // A server that handles client socket connections.
1483 class Server {
1484 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001485 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001486
Yifan Hong1deca4b2021-09-10 16:16:44 -07001487 explicit Server() {}
1488 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001489 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001490 [[nodiscard]] AssertionResult setUp(
1491 const Param& param,
1492 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001493 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001494 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001495 if (!rpcServer->setProtocolVersion(serverVersion)) {
1496 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1497 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001498 switch (socketType) {
1499 case SocketType::PRECONNECTED: {
1500 return AssertionFailure() << "Not supported by this test";
1501 } break;
1502 case SocketType::UNIX: {
1503 auto addr = allocateSocketAddress();
1504 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1505 if (status != OK) {
1506 return AssertionFailure()
1507 << "setupUnixDomainServer: " << statusToString(status);
1508 }
1509 mConnectToServer = [addr] {
1510 return connectTo(UnixSocketAddress(addr.c_str()));
1511 };
1512 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001513 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001514 unique_fd bootstrapFdClient, bootstrapFdServer;
1515 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001516 return AssertionFailure() << "Socketpair() failed";
1517 }
1518 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1519 std::move(bootstrapFdServer));
1520 if (status != OK) {
1521 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1522 << statusToString(status);
1523 }
1524 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1525 mAcceptConnection = &Server::recvmsgServerConnection;
1526 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1527 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001528 case SocketType::UNIX_RAW: {
1529 auto addr = allocateSocketAddress();
1530 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1531 if (status != OK) {
1532 return AssertionFailure()
1533 << "setupRawSocketServer: " << statusToString(status);
1534 }
1535 mConnectToServer = [addr] {
1536 return connectTo(UnixSocketAddress(addr.c_str()));
1537 };
1538 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539 case SocketType::VSOCK: {
1540 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001541 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001542 if (status != OK) {
1543 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1544 }
1545 mConnectToServer = [port] {
1546 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1547 };
1548 } break;
1549 case SocketType::INET: {
1550 unsigned int port;
1551 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1552 if (status != OK) {
1553 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1554 }
1555 mConnectToServer = [port] {
1556 const char* addr = kLocalInetAddress;
1557 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001558 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001559 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1560 auto fd = connectTo(
1561 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1562 if (fd.ok()) return fd;
1563 }
1564 ALOGE("None of the socket address resolved for %s:%u can be connected",
1565 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001566 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001567 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001568 } break;
1569 case SocketType::TIPC: {
1570 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1571 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001572 }
1573 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001574 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001575 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001576 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1577 mSetup = true;
1578 return AssertionSuccess();
1579 }
1580 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1581 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1582 return mCertVerifier;
1583 }
1584 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1585 void start() {
1586 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1587 mThread = std::make_unique<std::thread>(&Server::run, this);
1588 }
David Brazdil21c887c2022-09-23 12:25:18 +01001589
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001590 unique_fd acceptServerConnection() {
1591 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001592 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1593 }
1594
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001595 unique_fd recvmsgServerConnection() {
1596 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001597 int buf;
1598 iovec iov{&buf, sizeof(buf)};
1599
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001600 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001601 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001602 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001603 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1604 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001605 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001606 }
1607
Yifan Hong1deca4b2021-09-10 16:16:44 -07001608 void run() {
1609 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1610
1611 std::vector<std::thread> threads;
1612 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001613 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001614 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1615 }
1616
1617 for (auto& thread : threads) thread.join();
1618 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001619 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001621 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001622 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001624 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625 }
Yifan Honge07d2732021-09-13 21:59:14 -07001626 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001627 shutdown();
1628 join();
1629 }
1630 void shutdown() { mFdTrigger->trigger(); }
1631
1632 void setPostConnect(
1633 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1634 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001635 }
1636
1637 private:
1638 std::unique_ptr<std::thread> mThread;
1639 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001640 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001641 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001642 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001643 std::unique_ptr<RpcTransportCtx> mCtx;
1644 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1645 std::make_shared<RpcCertificateVerifierSimple>();
1646 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001647 // The function invoked after connection and handshake. By default, it is
1648 // |defaultPostConnect| that sends |kMessage| to the client.
1649 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1650 Server::defaultPostConnect;
1651
1652 void join() {
1653 if (mThread != nullptr) {
1654 mThread->join();
1655 mThread = nullptr;
1656 }
1657 }
1658
1659 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1660 FdTrigger* fdTrigger) {
1661 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001662 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001663 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001664 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001665 if (status != OK) return AssertionFailure() << statusToString(status);
1666 return AssertionSuccess();
1667 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001668 };
1669
1670 class Client {
1671 public:
1672 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1673 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001674 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001675 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1676 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001677 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001678 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001679 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1680 return AssertionSuccess();
1681 }
1682 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1683 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1684 return mCertVerifier;
1685 }
Yifan Hong67519322021-09-13 18:51:16 -07001686 // connect() and do handshake
1687 bool setUpTransport() {
1688 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001689 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001690 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1691 return mClientTransport != nullptr;
1692 }
1693 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1694 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1695 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001696 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001697 status_t readStatus =
1698 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001699 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001700 if (readStatus != OK) {
1701 return AssertionFailure() << statusToString(readStatus);
1702 }
1703 if (readMessage != expectedMessage) {
1704 return AssertionFailure()
1705 << "Expected " << expectedMessage << ", actual " << readMessage;
1706 }
1707 return AssertionSuccess();
1708 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001709 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001710 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001711 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1712 return;
1713 }
1714 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001715 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 }
1717
Pawan49d74cb2022-08-03 21:19:11 +00001718 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1719
Yifan Hong1deca4b2021-09-10 16:16:44 -07001720 private:
1721 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001722 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1724 std::unique_ptr<RpcTransportCtx> mCtx;
1725 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1726 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001727 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001728 };
1729
1730 // Make A trust B.
1731 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001732 static status_t trust(RpcSecurity rpcSecurity,
1733 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1734 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001736 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1737 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1738 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739 }
1740
1741 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001742};
1743
1744class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1745public:
1746 using Server = RpcTransportTestUtils::Server;
1747 using Client = RpcTransportTestUtils::Client;
1748 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001749 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001750 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001751 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001752 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753 return ret;
1754 }
1755 static std::vector<ParamType> getRpcTranportTestParams() {
1756 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001757 for (auto serverVersion : testVersions()) {
1758 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1759 for (auto rpcSecurity : RpcSecurityValues()) {
1760 switch (rpcSecurity) {
1761 case RpcSecurity::RAW: {
1762 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1763 } break;
1764 case RpcSecurity::TLS: {
1765 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1766 serverVersion);
1767 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1768 serverVersion);
1769 } break;
1770 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001771 }
1772 }
1773 }
1774 return ret;
1775 }
1776 template <typename A, typename B>
1777 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001778 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1779 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001780 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1781 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001782 void SetUp() override {
1783 if constexpr (!kEnableRpcThreads) {
1784 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1785 }
1786 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787};
1788
1789TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 auto server = std::make_unique<Server>();
1791 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001792
1793 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001794 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001795
1796 ASSERT_EQ(OK, trust(&client, server));
1797 ASSERT_EQ(OK, trust(server, &client));
1798
1799 server->start();
1800 client.run();
1801}
1802
1803TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001804 auto server = std::make_unique<Server>();
1805 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001806
1807 std::vector<Client> clients;
1808 for (int i = 0; i < 2; i++) {
1809 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001810 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001811 ASSERT_EQ(OK, trust(&client, server));
1812 ASSERT_EQ(OK, trust(server, &client));
1813 }
1814
1815 server->start();
1816 for (auto& client : clients) client.run();
1817}
1818
1819TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001820 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1821 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001822
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001823 auto untrustedServer = std::make_unique<Server>();
1824 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001825
1826 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001827 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001828
1829 ASSERT_EQ(OK, trust(untrustedServer, &client));
1830
1831 untrustedServer->start();
1832
1833 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1834 // the client can't verify the server's identity.
1835 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1836 client.run(handshakeOk);
1837}
1838TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001839 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1840 (void)serverVersion;
1841
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001842 auto validServer = std::make_unique<Server>();
1843 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001845 auto maliciousServer = std::make_unique<Server>();
1846 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001847
1848 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001850
1851 ASSERT_EQ(OK, trust(&client, validServer));
1852 ASSERT_EQ(OK, trust(validServer, &client));
1853 ASSERT_EQ(OK, trust(maliciousServer, &client));
1854
1855 maliciousServer->start();
1856
1857 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1858 // the client can't verify the server's identity.
1859 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1860 client.run(handshakeOk);
1861}
1862
1863TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001864 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1865 (void)serverVersion;
1866
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 auto server = std::make_unique<Server>();
1868 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869
1870 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001871 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001872
1873 ASSERT_EQ(OK, trust(&client, server));
1874
1875 server->start();
1876
1877 // For TLS, Client should be able to verify server's identity, so client should see
1878 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1879 // identity and should drop the connection, so client shouldn't be able to read anything.
1880 bool readOk = rpcSecurity != RpcSecurity::TLS;
1881 client.run(true, readOk);
1882}
1883
1884TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001885 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1886 (void)serverVersion;
1887
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001888 auto server = std::make_unique<Server>();
1889 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001890
1891 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001892 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001893 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001894 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895
1896 ASSERT_EQ(OK, trust(&validClient, server));
1897 ASSERT_EQ(OK, trust(&maliciousClient, server));
1898
1899 server->start();
1900
1901 // See UntrustedClient.
1902 bool readOk = rpcSecurity != RpcSecurity::TLS;
1903 maliciousClient.run(true, readOk);
1904}
1905
Yifan Hong67519322021-09-13 18:51:16 -07001906TEST_P(RpcTransportTest, Trigger) {
1907 std::string msg2 = ", world!";
1908 std::mutex writeMutex;
1909 std::condition_variable writeCv;
1910 bool shouldContinueWriting = false;
1911 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001912 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001913 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001914 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1915 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001916 if (status != OK) return AssertionFailure() << statusToString(status);
1917
1918 {
1919 std::unique_lock<std::mutex> lock(writeMutex);
1920 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1921 return AssertionFailure() << "write barrier not cleared in time!";
1922 }
1923 }
1924
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001925 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001926 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1927 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001928 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001929 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001930 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001931 << statusToString(status);
1932 return AssertionSuccess();
1933 };
1934
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001935 auto server = std::make_unique<Server>();
1936 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001937
1938 // Set up client
1939 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001940 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001941
1942 // Exchange keys
1943 ASSERT_EQ(OK, trust(&client, server));
1944 ASSERT_EQ(OK, trust(server, &client));
1945
1946 server->setPostConnect(serverPostConnect);
1947
Yifan Hong67519322021-09-13 18:51:16 -07001948 server->start();
1949 // connect() to server and do handshake
1950 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001951 // read the first message. This ensures that server has finished handshake and start handling
1952 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001953 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001954 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1955 // write is on an FdTrigger that has been shut down.
1956 server->shutdown();
1957 // Continues server thread to write the second message.
1958 {
Yifan Hong22211f82021-09-14 12:32:25 -07001959 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001960 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001961 }
Yifan Hong22211f82021-09-14 12:32:25 -07001962 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001963 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001964 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001965 // On the client side, second read fails with DEAD_OBJECT
1966 ASSERT_FALSE(client.readMessage(msg2));
1967}
1968
Pawan49d74cb2022-08-03 21:19:11 +00001969TEST_P(RpcTransportTest, CheckWaitingForRead) {
1970 std::mutex readMutex;
1971 std::condition_variable readCv;
1972 bool shouldContinueReading = false;
1973 // Server will write data on transport once its started
1974 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1975 std::string message(RpcTransportTestUtils::kMessage);
1976 iovec messageIov{message.data(), message.size()};
1977 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1978 std::nullopt, nullptr);
1979 if (status != OK) return AssertionFailure() << statusToString(status);
1980
1981 {
1982 std::unique_lock<std::mutex> lock(readMutex);
1983 shouldContinueReading = true;
1984 lock.unlock();
1985 readCv.notify_all();
1986 }
1987 return AssertionSuccess();
1988 };
1989
1990 // Setup Server and client
1991 auto server = std::make_unique<Server>();
1992 ASSERT_TRUE(server->setUp(GetParam()));
1993
1994 Client client(server->getConnectToServerFn());
1995 ASSERT_TRUE(client.setUp(GetParam()));
1996
1997 ASSERT_EQ(OK, trust(&client, server));
1998 ASSERT_EQ(OK, trust(server, &client));
1999 server->setPostConnect(serverPostConnect);
2000
2001 server->start();
2002 ASSERT_TRUE(client.setUpTransport());
2003 {
2004 // Wait till server writes data
2005 std::unique_lock<std::mutex> lock(readMutex);
2006 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2007 }
2008
2009 // Since there is no read polling here, we will get polling count 0
2010 ASSERT_FALSE(client.isTransportWaiting());
2011 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2012 // Thread should increment polling count, read and decrement polling count
2013 // Again, polling count should be zero here
2014 ASSERT_FALSE(client.isTransportWaiting());
2015
2016 server->shutdown();
2017}
2018
Yifan Hong1deca4b2021-09-10 16:16:44 -07002019INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002020 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002021 RpcTransportTest::PrintParamInfo);
2022
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002024 : public testing::TestWithParam<
2025 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026public:
2027 template <typename A, typename B>
2028 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002029 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2030 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002031 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2032 }
2033 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002034 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2035 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2036 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002037 };
2038};
2039
2040TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002041 if constexpr (!kEnableRpcThreads) {
2042 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2043 }
2044
Frederick Mayledc07cf82022-05-26 20:30:12 +00002045 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002046
2047 std::vector<uint8_t> pkeyData, certData;
2048 {
2049 auto pkey = makeKeyPairForSelfSignedCert();
2050 ASSERT_NE(nullptr, pkey);
2051 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2052 ASSERT_NE(nullptr, cert);
2053 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2054 certData = serializeCertificate(cert.get(), certificateFormat);
2055 }
2056
2057 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2058 auto desCert = deserializeCertificate(certData, certificateFormat);
2059 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002060 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2061 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002062
2063 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2064 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2065
2066 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2067 ASSERT_TRUE(client.setUp(utilsParam));
2068
2069 ASSERT_EQ(OK, trust(&client, server));
2070 ASSERT_EQ(OK, trust(server, &client));
2071
2072 server->start();
2073 client.run();
2074}
2075
2076INSTANTIATE_TEST_CASE_P(
2077 BinderRpc, RpcTransportTlsKeyTest,
2078 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2079 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002080 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2081 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002082 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002083#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002084
Steven Morelandc1635952021-04-01 16:20:47 +00002085} // namespace android
2086
2087int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002088 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002089 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002090
Steven Moreland5553ac42020-11-11 02:14:45 +00002091 return RUN_ALL_TESTS();
2092}