blob: cd78e82322fa770e7bec941b7724f9a213e76a83 [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
Devin Moore1df9c5f2024-07-23 22:09:29 +000022#if defined(__LP64__)
23#define TEST_FILE_SUFFIX "64"
24#else
25#define TEST_FILE_SUFFIX "32"
26#endif
27
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <chrono>
29#include <cstdlib>
30#include <iostream>
31#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000032#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000033
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070034#include <dirent.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000035#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070036#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000038#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000039
Andrei Homescud65666d2023-03-03 07:28:02 +000040#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000041#include <binder/RpcTransportTipcAndroid.h>
42#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000043#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000044
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -080045#include "../Utils.h"
Andrei Homescu2a298012022-06-15 01:08:54 +000046#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000047#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000048
Yifan Hong1a235852021-05-13 16:07:47 -070049using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070050using namespace std::placeholders;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070051using android::binder::borrowed_fd;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -070052using android::binder::GetExecutableDirectory;
53using android::binder::ReadFdToString;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070054using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070055using testing::AssertionFailure;
56using testing::AssertionResult;
57using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070058
Steven Moreland5553ac42020-11-11 02:14:45 +000059namespace android {
60
Andrei Homescu12106de2022-04-27 04:42:21 +000061#ifdef BINDER_TEST_NO_SHARED_LIBS
62constexpr bool kEnableSharedLibs = false;
63#else
64constexpr bool kEnableSharedLibs = true;
65#endif
66
Andrei Homescud65666d2023-03-03 07:28:02 +000067#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000068constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
69#endif
70
Frederick Maylea12b0962022-06-25 01:13:22 +000071static std::string WaitStatusToString(int wstatus) {
72 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070073 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000074 }
75 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070076 return "term signal " + std::to_string(WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000077 }
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070078 return "unexpected state " + std::to_string(wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000079}
80
Steven Moreland276d8df2022-09-28 23:56:39 +000081static void debugBacktrace(pid_t pid) {
82 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
83 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
84}
85
Steven Moreland5553ac42020-11-11 02:14:45 +000086class Process {
87public:
Andrei Homescu96834632022-10-14 00:49:49 +000088 Process(Process&& other)
89 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
90 mReadEnd(std::move(other.mReadEnd)),
91 mWriteEnd(std::move(other.mWriteEnd)) {
92 // The default move constructor doesn't clear mPid after moving it,
93 // which we need to do because the destructor checks for mPid!=0
94 mPid = other.mPid;
95 other.mPid = 0;
96 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070097 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
98 unique_fd childWriteEnd;
99 unique_fd childReadEnd;
100 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
101 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +0000102 if (0 == (mPid = fork())) {
103 // racey: assume parent doesn't crash before this is set
104 prctl(PR_SET_PDEATHSIG, SIGHUP);
105
Yifan Hong1deca4b2021-09-10 16:16:44 -0700106 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000107
108 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 }
110 }
111 ~Process() {
112 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 int wstatus;
114 waitpid(mPid, &wstatus, 0);
115 if (mCustomExitStatusCheck) {
116 mCustomExitStatusCheck(wstatus);
117 } else {
118 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
119 << "server process failed: " << WaitStatusToString(wstatus);
120 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000121 }
122 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700123 borrowed_fd readEnd() { return mReadEnd; }
124 borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000125
Frederick Maylea12b0962022-06-25 01:13:22 +0000126 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
127 mCustomExitStatusCheck = std::move(f);
128 }
129
Frederick Mayle69a0c992022-05-26 20:38:39 +0000130 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
131 void terminate() { kill(mPid, SIGTERM); }
132
Steven Moreland276d8df2022-09-28 23:56:39 +0000133 pid_t getPid() { return mPid; }
134
Steven Moreland5553ac42020-11-11 02:14:45 +0000135private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000136 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 pid_t mPid = 0;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700138 unique_fd mReadEnd;
139 unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000140};
141
142static std::string allocateSocketAddress() {
143 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000144 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000145 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700146 unlink(ret.c_str());
147 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000148};
149
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700150static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000151 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700152 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700153 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
154 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
155 PLOGF("initUnixSocket failed to bind");
156 }
Alice Wang893a9912022-10-24 10:44:09 +0000157 return fd;
158}
159
Andrei Homescu96834632022-10-14 00:49:49 +0000160// Destructors need to be defined, even if pure virtual
161ProcessSession::~ProcessSession() {}
162
163class LinuxProcessSession : public ProcessSession {
164public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000165 // reference to process hosting a socket server
166 Process host;
167
Andrei Homescu96834632022-10-14 00:49:49 +0000168 LinuxProcessSession(LinuxProcessSession&&) = default;
169 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
170 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 for (auto& session : sessions) {
172 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000173 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000174
Steven Moreland67f85902023-03-15 01:13:49 +0000175 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
176 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000178
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 EXPECT_NE(nullptr, session);
180 EXPECT_NE(nullptr, session->state());
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700181 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000182
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183 wp<RpcSession> weakSession = session;
184 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000185
Steven Moreland57042712022-10-04 23:56:45 +0000186 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
187 // the object should not actually be promotable. By looping, we distinguish a race here
188 // from a bug causing the object to not be promotable.
189 for (size_t i = 0; i < 3; i++) {
190 sp<RpcSession> strongSession = weakSession.promote();
191 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000192 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000193 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
194 "Leaked sess: ")
195 << strongSession->getStrongCount() << " checked time " << i;
196
197 if (strongSession != nullptr) {
198 sleep(1);
199 }
200 }
Steven Moreland736664b2021-05-01 04:27:25 +0000201 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000202 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000203
Andrei Homescu96834632022-10-14 00:49:49 +0000204 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
205 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000206 }
Andrei Homescu96834632022-10-14 00:49:49 +0000207
208 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000209};
210
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700211static unique_fd connectTo(const RpcSocketAddress& addr) {
212 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700213 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700214 if (!serverFd.ok()) {
215 PLOGF("Could not create socket %s", addr.toString().c_str());
216 }
Steven Moreland4198a122021-08-03 17:37:58 -0700217
218 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700219 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700220 }
221 return serverFd;
222}
223
Andrei Homescud65666d2023-03-03 07:28:02 +0000224#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700225static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
226 unique_fd sockClient, sockServer;
227 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700228 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100229 }
230
231 int zero = 0;
232 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700233 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100234 fds.emplace_back(std::move(sockServer));
235
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000236 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700237 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100238 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700239 return sockClient;
David Brazdil21c887c2022-09-23 12:25:18 +0100240}
Andrei Homescud65666d2023-03-03 07:28:02 +0000241#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100242
Andrei Homescuf30148c2023-03-10 00:31:45 +0000243std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
244 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000245}
Andrei Homescu2a298012022-06-15 01:08:54 +0000246
Andrei Homescu96834632022-10-14 00:49:49 +0000247// This creates a new process serving an interface on a certain number of
248// threads.
249std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
250 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700251 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000252
Steven Moreland67f85902023-03-15 01:13:49 +0000253 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700254 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
255 "%s: %zu != %zu", __func__,
256 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000257 }
258
Steven Morelandb469f432023-07-28 22:13:47 +0000259 SocketType socketType = GetParam().type;
260 RpcSecurity rpcSecurity = GetParam().security;
261 uint32_t clientVersion = GetParam().clientVersion;
262 uint32_t serverVersion = GetParam().serverVersion;
263 bool singleThreaded = GetParam().singleThreaded;
264 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000265
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700266 std::string path = GetExecutableDirectory();
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -0700267 auto servicePath = path + "/binder_rpc_test_service" +
Devin Moore1df9c5f2024-07-23 22:09:29 +0000268 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "") +
269 TEST_FILE_SUFFIX;
Andrei Homescu96834632022-10-14 00:49:49 +0000270
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700271 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000272
Alice Wang893a9912022-10-24 10:44:09 +0000273 auto addr = allocateSocketAddress();
274 // Initializes the socket before the fork/exec.
275 if (socketType == SocketType::UNIX_RAW) {
276 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000277 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
278 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
279 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700280 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700281 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000282 }
Alice Wang893a9912022-10-24 10:44:09 +0000283 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000284
Andrei Homescu96834632022-10-14 00:49:49 +0000285 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700286 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000287 if (socketType == SocketType::TIPC) {
288 // Trusty has a single persistent service
289 return;
290 }
291
Andrei Homescu96834632022-10-14 00:49:49 +0000292 auto writeFd = std::to_string(writeEnd.get());
293 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800294 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
295 readFd.c_str(), NULL);
296 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
297 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000298 }));
299
300 BinderRpcTestServerConfig serverConfig;
301 serverConfig.numThreads = options.numThreads;
302 serverConfig.socketType = static_cast<int32_t>(socketType);
303 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
304 serverConfig.serverVersion = serverVersion;
Alice Wang893a9912022-10-24 10:44:09 +0000305 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000306 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000307 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
308 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
309 static_cast<int32_t>(mode));
310 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 if (socketType != SocketType::TIPC) {
312 writeToFd(ret->host.writeEnd(), serverConfig);
313 }
Andrei Homescu96834632022-10-14 00:49:49 +0000314
315 std::vector<sp<RpcSession>> sessions;
316 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
317 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000318 std::unique_ptr<RpcTransportCtxFactory> factory;
319 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000320#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000321 factory = RpcTransportCtxFactoryTipcAndroid::make();
322#else
323 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
324#endif
325 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000326 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000327 }
328 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100329 }
330
Andrei Homescu68a55612022-08-02 01:25:15 +0000331 BinderRpcTestServerInfo serverInfo;
332 if (socketType != SocketType::TIPC) {
333 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
334 BinderRpcTestClientInfo clientInfo;
335 for (const auto& session : sessions) {
336 auto& parcelableCert = clientInfo.certs.emplace_back();
337 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
338 }
339 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000340
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700341 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000342 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700343 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000344 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000345
Andrei Homescu68a55612022-08-02 01:25:15 +0000346 if (rpcSecurity == RpcSecurity::TLS) {
347 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700348 LOG_ALWAYS_FATAL_IF(
349 OK !=
350 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000351 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 }
353
Andrei Homescu96834632022-10-14 00:49:49 +0000354 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000355
Steven Moreland67f85902023-03-15 01:13:49 +0000356 for (size_t i = 0; i < sessions.size(); i++) {
357 const auto& session = sessions.at(i);
358
359 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
360 ? options.numIncomingConnectionsBySession.at(i)
361 : 0;
362
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700363 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000364 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000365 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000366 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000367
Andrei Homescu96834632022-10-14 00:49:49 +0000368 switch (socketType) {
369 case SocketType::PRECONNECTED:
370 status = session->setupPreconnectedClient({}, [=]() {
371 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
372 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000373 break;
Alice Wang893a9912022-10-24 10:44:09 +0000374 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000375 case SocketType::UNIX:
376 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
377 break;
378 case SocketType::UNIX_BOOTSTRAP:
379 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700380 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000381 break;
382 case SocketType::VSOCK:
Tomasz Wasilczyk022db682024-06-17 13:55:51 -0700383 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverInfo.port);
Andrei Homescu96834632022-10-14 00:49:49 +0000384 break;
385 case SocketType::INET:
386 status = session->setupInetClient("127.0.0.1", serverInfo.port);
387 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000388 case SocketType::TIPC:
389 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000390#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000391 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000392 for (size_t i = 0; i < 5; i++) {
393 // Try to connect several times,
394 // in case the service is slow to start
395 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
396 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700397 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000398 }
399 usleep(50000);
400 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700401 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000402#else
403 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700404 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000405#endif
406 });
407 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000408 default:
409 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000410 }
Andrei Homescu96834632022-10-14 00:49:49 +0000411 if (options.allowConnectFailure && status != OK) {
412 ret->sessions.clear();
413 break;
414 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700415 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Andrei Homescu96834632022-10-14 00:49:49 +0000416 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000417 }
Andrei Homescu96834632022-10-14 00:49:49 +0000418 return ret;
419}
Steven Morelandc1635952021-04-01 16:20:47 +0000420
Andrei Homescua858b0e2022-08-01 23:43:09 +0000421TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
422 if (clientOrServerSingleThreaded()) {
423 GTEST_SKIP() << "This test requires multiple threads";
424 }
425
Steven Moreland5553ac42020-11-11 02:14:45 +0000426 constexpr size_t kNumThreads = 10;
427
Steven Moreland4313d7e2021-07-15 23:41:22 +0000428 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000429
430 EXPECT_OK(proc.rootIface->lock());
431
432 // block all but one thread taking locks
433 std::vector<std::thread> ts;
434 for (size_t i = 0; i < kNumThreads - 1; i++) {
435 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
436 }
437
Steven Morelandd6d816f2022-12-23 01:37:17 +0000438 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000439
440 // other calls still work
441 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
442
Steven Morelandd6d816f2022-12-23 01:37:17 +0000443 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000444 size_t epochMsBefore = epochMillis();
445 // after this, we should never see a response within this time
446 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
447
448 // this call should be blocked for blockTimeMs
449 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
450
451 size_t epochMsAfter = epochMillis();
452 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
453
454 for (auto& t : ts) t.join();
455}
456
Steven Moreland27f620a2023-03-06 19:44:36 +0000457static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000458 size_t epochMsBefore = epochMillis();
459
460 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700461 for (size_t i = 0; i < numCalls; i++) {
462 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000463 }
464
465 for (auto& t : ts) t.join();
466
467 size_t epochMsAfter = epochMillis();
468
Yifan Hong1f44f982021-10-08 17:16:47 -0700469 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000470
Steven Moreland9c203222023-05-31 21:26:41 +0000471 // Potential flake, but make sure calls are handled in parallel. Due
472 // to past flakes, this only checks that the amount of time taken has
473 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
474 // check this more exactly.
475 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700476}
477
Andrei Homescua858b0e2022-08-01 23:43:09 +0000478TEST_P(BinderRpc, ThreadPoolOverSaturated) {
479 if (clientOrServerSingleThreaded()) {
480 GTEST_SKIP() << "This test requires multiple threads";
481 }
482
Yifan Hong1f44f982021-10-08 17:16:47 -0700483 constexpr size_t kNumThreads = 10;
484 constexpr size_t kNumCalls = kNumThreads + 3;
485 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000486
487 // b/272429574 - below 500ms, the test fails
488 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700489}
490
Andrei Homescua858b0e2022-08-01 23:43:09 +0000491TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
492 if (clientOrServerSingleThreaded()) {
493 GTEST_SKIP() << "This test requires multiple threads";
494 }
495
Yifan Hong1f44f982021-10-08 17:16:47 -0700496 constexpr size_t kNumThreads = 20;
497 constexpr size_t kNumOutgoingConnections = 10;
498 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
499 auto proc = createRpcTestSocketServerProcess(
500 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000501
502 // b/272429574 - below 500ms, the test fails
503 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000504}
505
Andrei Homescua858b0e2022-08-01 23:43:09 +0000506TEST_P(BinderRpc, ThreadingStressTest) {
507 if (clientOrServerSingleThreaded()) {
508 GTEST_SKIP() << "This test requires multiple threads";
509 }
510
Steven Moreland27f620a2023-03-06 19:44:36 +0000511 constexpr size_t kNumClientThreads = 5;
512 constexpr size_t kNumServerThreads = 5;
513 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000514
Steven Moreland4313d7e2021-07-15 23:41:22 +0000515 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000516
517 std::vector<std::thread> threads;
518 for (size_t i = 0; i < kNumClientThreads; i++) {
519 threads.push_back(std::thread([&] {
520 for (size_t j = 0; j < kNumCalls; j++) {
521 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000522 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000523 EXPECT_EQ(proc.rootBinder, out);
524 }
525 }));
526 }
527
528 for (auto& t : threads) t.join();
529}
530
Steven Moreland925ba0a2021-09-17 18:06:32 -0700531static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
532 std::vector<std::thread> threads;
533 for (size_t i = 0; i < threadCount; i++) {
534 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
535 }
536 for (auto& t : threads) t.join();
537}
538
Andrei Homescua858b0e2022-08-01 23:43:09 +0000539TEST_P(BinderRpc, OnewayStressTest) {
540 if (clientOrServerSingleThreaded()) {
541 GTEST_SKIP() << "This test requires multiple threads";
542 }
543
Steven Morelandc6046982021-04-20 00:49:42 +0000544 constexpr size_t kNumClientThreads = 10;
545 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700546 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000547
Steven Moreland4313d7e2021-07-15 23:41:22 +0000548 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000549
550 std::vector<std::thread> threads;
551 for (size_t i = 0; i < kNumClientThreads; i++) {
552 threads.push_back(std::thread([&] {
553 for (size_t j = 0; j < kNumCalls; j++) {
554 EXPECT_OK(proc.rootIface->sendString("a"));
555 }
Steven Morelandc6046982021-04-20 00:49:42 +0000556 }));
557 }
558
559 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700560
561 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000562}
563
Frederick Mayleb0221d12022-10-03 23:10:53 +0000564TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
565 if (!supportsFdTransport()) {
566 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
567 }
568 if (clientOrServerSingleThreaded()) {
569 GTEST_SKIP() << "This test requires multiple threads";
570 }
571
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000572 constexpr size_t kNumServerThreads = 3;
573
Frederick Mayleb0221d12022-10-03 23:10:53 +0000574 // This test forces a oneway transaction to be queued by issuing two
575 // `blockingSendFdOneway` calls, then drains the queue by issuing two
576 // `blockingRecvFd` calls.
577 //
578 // For more details about the queuing semantics see
579 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
580
581 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000582 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000583 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
584 .serverSupportedFileDescriptorTransportModes =
585 {RpcSession::FileDescriptorTransportMode::UNIX},
586 });
587
588 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
589 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
590 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
591 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
592
593 android::os::ParcelFileDescriptor fdA;
594 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
595 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700596 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000597 EXPECT_EQ(result, "a");
598
599 android::os::ParcelFileDescriptor fdB;
600 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700601 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000602 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000603
604 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000605}
606
Andrei Homescua858b0e2022-08-01 23:43:09 +0000607TEST_P(BinderRpc, OnewayCallQueueing) {
608 if (clientOrServerSingleThreaded()) {
609 GTEST_SKIP() << "This test requires multiple threads";
610 }
611
Frederick Mayle96872592023-03-07 14:56:15 -0800612 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000614
615 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000616 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000617
Frederick Mayle96872592023-03-07 14:56:15 -0800618 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700619 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800620 for (size_t i = 0; i + 1 < kNumQueued; i++) {
621 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 }
Frederick Mayle96872592023-03-07 14:56:15 -0800623 for (size_t i = 0; i + 1 < kNumQueued; i++) {
624 int n;
625 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700626 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800627 }
Steven Morelandf5174272021-05-25 00:39:28 +0000628
Steven Moreland925ba0a2021-09-17 18:06:32 -0700629 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000630}
631
Andrei Homescua858b0e2022-08-01 23:43:09 +0000632TEST_P(BinderRpc, OnewayCallExhaustion) {
633 if (clientOrServerSingleThreaded()) {
634 GTEST_SKIP() << "This test requires multiple threads";
635 }
636
Steven Morelandd45be622021-06-04 02:19:37 +0000637 constexpr size_t kNumClients = 2;
638 constexpr size_t kTooLongMs = 1000;
639
Steven Moreland4313d7e2021-07-15 23:41:22 +0000640 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000641
642 // Build up oneway calls on the second session to make sure it terminates
643 // and shuts down. The first session should be unaffected (proc destructor
644 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000645 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000646
647 std::vector<std::thread> threads;
648 for (size_t i = 0; i < kNumClients; i++) {
649 // one of these threads will get stuck queueing a transaction once the
650 // socket fills up, the other will be able to fill up transactions on
651 // this object
652 threads.push_back(std::thread([&] {
653 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
654 }
655 }));
656 }
657 for (auto& t : threads) t.join();
658
659 Status status = iface->sleepMsAsync(kTooLongMs);
660 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
661
Steven Moreland798e0d12021-07-14 23:19:25 +0000662 // now that it has died, wait for the remote session to shutdown
663 std::vector<int32_t> remoteCounts;
664 do {
665 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
666 } while (remoteCounts.size() == kNumClients);
667
Steven Morelandd45be622021-06-04 02:19:37 +0000668 // the second session should be shutdown in the other process by the time we
669 // are able to join above (it'll only be hung up once it finishes processing
670 // any pending commands). We need to erase this session from the record
671 // here, so that the destructor for our session won't check that this
672 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000673 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000674}
675
Steven Moreland67f85902023-03-15 01:13:49 +0000676TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
677 if (clientOrServerSingleThreaded()) {
678 GTEST_SKIP() << "This test requires multiple threads";
679 }
680
681 // session 0 - will check for leaks in destrutor of proc
682 // session 1 - we want to make sure it gets deleted when we drop all references to it
683 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700684 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000685
686 wp<RpcSession> session = proc.proc->sessions.at(1).session;
687
688 // remove all references to the second session
689 proc.proc->sessions.at(1).root = nullptr;
690 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
691
692 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
693 // to drain commands.
694 for (size_t i = 0; i < 100; i++) {
695 usleep(10 * 1000);
696 if (session.promote() == nullptr) break;
697 }
698
699 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000700
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000701 // now that it has died, wait for the remote session to shutdown
702 std::vector<int32_t> remoteCounts;
703 do {
704 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
705 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000706}
707
Devin Moore66d5b7a2022-07-07 21:42:10 +0000708TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000709 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000710 GTEST_SKIP() << "This test requires multiple threads";
711 }
712 class MyDeathRec : public IBinder::DeathRecipient {
713 public:
714 void binderDied(const wp<IBinder>& /* who */) override {
715 dead = true;
716 mCv.notify_one();
717 }
718 std::mutex mMtx;
719 std::condition_variable mCv;
720 bool dead = false;
721 };
722
723 // Death recipient needs to have an incoming connection to be called
724 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000725 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000726
727 auto dr = sp<MyDeathRec>::make();
728 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
729
730 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
731 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
732 }
733
734 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000735 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000736
737 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000738 // can't do this before checking the death recipient by calling
739 // forceShutdown earlier, because shutdownAndWait will also trigger
740 // a death recipient, but if we had a way to wait for the service
741 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000742 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000743 proc.expectAlreadyShutdown = true;
744}
745
746TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000747 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000748 GTEST_SKIP() << "This test requires multiple threads";
749 }
750 class MyDeathRec : public IBinder::DeathRecipient {
751 public:
752 void binderDied(const wp<IBinder>& /* who */) override {
753 dead = true;
754 mCv.notify_one();
755 }
756 std::mutex mMtx;
757 std::condition_variable mCv;
758 bool dead = false;
759 };
760
761 // Death recipient needs to have an incoming connection to be called
762 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000763 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000764
765 auto dr = sp<MyDeathRec>::make();
766 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
767
768 // Explicitly calling shutDownAndWait will cause the death recipients
769 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000770 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000771
772 std::unique_lock<std::mutex> lock(dr->mMtx);
773 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000774 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000775 }
776 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
777
Andrei Homescu96834632022-10-14 00:49:49 +0000778 proc.proc->terminate();
779 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000780 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
781 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
782 });
783 proc.expectAlreadyShutdown = true;
784}
785
Steven Moreland5ec743f2023-01-18 01:02:06 +0000786TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000787 if (socketType() == SocketType::TIPC) {
788 // This should work, but Trusty takes too long to restart the service
789 GTEST_SKIP() << "Service death test not supported on Trusty";
790 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000791 class MyDeathRec : public IBinder::DeathRecipient {
792 public:
793 void binderDied(const wp<IBinder>& /* who */) override {}
794 };
795
Steven Moreland67f85902023-03-15 01:13:49 +0000796 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000797
798 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000799 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000800}
801
802TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000803 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000804 GTEST_SKIP() << "This test requires multiple threads";
805 }
806 class MyDeathRec : public IBinder::DeathRecipient {
807 public:
808 void binderDied(const wp<IBinder>& /* who */) override {
809 GTEST_FAIL() << "This should not be called after unlinkToDeath";
810 }
811 };
812
813 // Death recipient needs to have an incoming connection to be called
814 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000815 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000816
817 auto dr = sp<MyDeathRec>::make();
818 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
819 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
820
Steven Moreland67f85902023-03-15 01:13:49 +0000821 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000822}
823
Steven Morelandc1635952021-04-01 16:20:47 +0000824TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000825 if (socketType() == SocketType::TIPC) {
826 // This should work, but Trusty takes too long to restart the service
827 GTEST_SKIP() << "Service death test not supported on Trusty";
828 }
829
Steven Moreland5553ac42020-11-11 02:14:45 +0000830 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000831 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000832
833 // make sure there is some state during crash
834 // 1. we hold their binder
835 sp<IBinderRpcSession> session;
836 EXPECT_OK(proc.rootIface->openSession("happy", &session));
837 // 2. they hold our binder
838 sp<IBinder> binder = new BBinder();
839 EXPECT_OK(proc.rootIface->holdBinder(binder));
840
841 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
842 << "Do death cleanup: " << doDeathCleanup;
843
Andrei Homescu96834632022-10-14 00:49:49 +0000844 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000845 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
846 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
847 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000848 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000849 }
850}
851
Steven Morelandd7302072021-05-15 01:32:04 +0000852TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000853 // This test only works if the current process shared the internal state of
854 // ProcessState with the service across the call to fork(). Both the static
855 // libraries and libbinder.so have their own separate copies of all the
856 // globals, so the test only works when the test client and service both use
857 // libbinder.so (when using static libraries, even a client and service
858 // using the same kind of static library should have separate copies of the
859 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000860 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000861 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
862 "at build time.";
863 }
864
Steven Moreland4313d7e2021-07-15 23:41:22 +0000865 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000866
Andrei Homescu2a298012022-06-15 01:08:54 +0000867 // we can't allocate IPCThreadState so actually the first time should
868 // succeed :(
869 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000870
871 // second time! we catch the error :)
872 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
873
Andrei Homescu96834632022-10-14 00:49:49 +0000874 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000875 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
876 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
877 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000878 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000879}
880
Frederick Mayle69a0c992022-05-26 20:38:39 +0000881TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000882 if (socketType() == SocketType::TIPC) {
883 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
884 }
885
Frederick Mayle69a0c992022-05-26 20:38:39 +0000886 auto proc = createRpcTestSocketServerProcess({
887 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
888 .serverSupportedFileDescriptorTransportModes =
889 {RpcSession::FileDescriptorTransportMode::UNIX},
890 .allowConnectFailure = true,
891 });
Andrei Homescu96834632022-10-14 00:49:49 +0000892 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
893 proc.proc->terminate();
894 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000895 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
896 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
897 });
898 proc.expectAlreadyShutdown = true;
899}
900
901TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000902 if (socketType() == SocketType::TIPC) {
903 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
904 }
905
Frederick Mayle69a0c992022-05-26 20:38:39 +0000906 auto proc = createRpcTestSocketServerProcess({
907 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
908 .serverSupportedFileDescriptorTransportModes =
909 {RpcSession::FileDescriptorTransportMode::NONE},
910 .allowConnectFailure = true,
911 });
Andrei Homescu96834632022-10-14 00:49:49 +0000912 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
913 proc.proc->terminate();
914 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000915 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
916 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
917 });
918 proc.expectAlreadyShutdown = true;
919}
920
921TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000922 if (socketType() == SocketType::TIPC) {
923 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
924 }
925
Frederick Mayle69a0c992022-05-26 20:38:39 +0000926 auto proc = createRpcTestSocketServerProcess({
927 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
928 .serverSupportedFileDescriptorTransportModes =
929 {RpcSession::FileDescriptorTransportMode::NONE,
930 RpcSession::FileDescriptorTransportMode::UNIX},
931 });
932
933 android::os::ParcelFileDescriptor out;
934 auto status = proc.rootIface->echoAsFile("hello", &out);
935 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
936}
937
938TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000939 if (socketType() == SocketType::TIPC) {
940 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
941 }
942
Frederick Mayle69a0c992022-05-26 20:38:39 +0000943 auto proc = createRpcTestSocketServerProcess({
944 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
945 .serverSupportedFileDescriptorTransportModes =
946 {RpcSession::FileDescriptorTransportMode::UNIX},
947 });
948
949 android::os::ParcelFileDescriptor out;
950 auto status = proc.rootIface->echoAsFile("hello", &out);
951 if (!supportsFdTransport()) {
952 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
953 return;
954 }
955 ASSERT_TRUE(status.isOk()) << status;
956
957 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700958 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700959 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000960}
961
962TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000963 if (socketType() == SocketType::TIPC) {
964 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
965 }
966
Frederick Mayle69a0c992022-05-26 20:38:39 +0000967 auto proc = createRpcTestSocketServerProcess({
968 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
969 .serverSupportedFileDescriptorTransportModes =
970 {RpcSession::FileDescriptorTransportMode::UNIX},
971 });
972
973 std::vector<android::os::ParcelFileDescriptor> files;
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
975 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
976 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
977 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
978
979 android::os::ParcelFileDescriptor out;
980 auto status = proc.rootIface->concatFiles(files, &out);
981 if (!supportsFdTransport()) {
982 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
983 return;
984 }
985 ASSERT_TRUE(status.isOk()) << status;
986
987 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700988 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000989 EXPECT_EQ(result, "123abcd");
990}
991
992TEST_P(BinderRpc, SendMaxFiles) {
993 if (!supportsFdTransport()) {
994 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
995 }
996
997 auto proc = createRpcTestSocketServerProcess({
998 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
999 .serverSupportedFileDescriptorTransportModes =
1000 {RpcSession::FileDescriptorTransportMode::UNIX},
1001 });
1002
1003 std::vector<android::os::ParcelFileDescriptor> files;
1004 for (int i = 0; i < 253; i++) {
1005 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1006 }
1007
1008 android::os::ParcelFileDescriptor out;
1009 auto status = proc.rootIface->concatFiles(files, &out);
1010 ASSERT_TRUE(status.isOk()) << status;
1011
1012 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001013 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001014 EXPECT_EQ(result, std::string(253, 'a'));
1015}
1016
1017TEST_P(BinderRpc, SendTooManyFiles) {
1018 if (!supportsFdTransport()) {
1019 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1020 }
1021
1022 auto proc = createRpcTestSocketServerProcess({
1023 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1024 .serverSupportedFileDescriptorTransportModes =
1025 {RpcSession::FileDescriptorTransportMode::UNIX},
1026 });
1027
1028 std::vector<android::os::ParcelFileDescriptor> files;
1029 for (int i = 0; i < 254; i++) {
1030 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1031 }
1032
1033 android::os::ParcelFileDescriptor out;
1034 auto status = proc.rootIface->concatFiles(files, &out);
1035 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1036}
1037
Andrei Homescufc221502022-10-08 03:51:17 +00001038TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001039 if (socketType() == SocketType::TIPC) {
1040 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1041 }
1042
Andrei Homescufc221502022-10-08 03:51:17 +00001043 auto proc = createRpcTestSocketServerProcess({
1044 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1045 .serverSupportedFileDescriptorTransportModes =
1046 {RpcSession::FileDescriptorTransportMode::UNIX},
1047 });
1048
1049 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1050 ASSERT_NE(badFd, -1);
1051
1052 // Close the file descriptor so it becomes invalid for dup
1053 close(badFd);
1054
1055 Parcel p1;
1056 p1.markForBinder(proc.rootBinder);
1057 p1.writeInt32(3);
1058 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1059
1060 Parcel pRaw;
1061 pRaw.markForBinder(proc.rootBinder);
1062 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1063
1064 pRaw.setDataPosition(0);
1065 EXPECT_EQ(3, pRaw.readInt32());
1066 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1067}
1068
Andrei Homescu68a55612022-08-02 01:25:15 +00001069#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001070TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001071 if constexpr (!kEnableSharedLibs) {
1072 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1073 }
1074
Steven Moreland4313d7e2021-07-15 23:41:22 +00001075 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001076
1077 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1078 ASSERT_NE(binder, nullptr);
1079
1080 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1081}
1082
1083TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001084 if constexpr (!kEnableSharedLibs) {
1085 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1086 }
1087
Steven Moreland4313d7e2021-07-15 23:41:22 +00001088 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001089
1090 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1091 ASSERT_NE(binder, nullptr);
1092
1093 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1094 ASSERT_NE(ndkBinder, nullptr);
1095
1096 std::string out;
1097 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1098 ASSERT_TRUE(status.isOk()) << status.getDescription();
1099 ASSERT_EQ("aoeuaoeu", out);
1100}
Andrei Homescu68a55612022-08-02 01:25:15 +00001101#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001102
Steven Moreland5553ac42020-11-11 02:14:45 +00001103ssize_t countFds() {
1104 DIR* dir = opendir("/proc/self/fd/");
1105 if (dir == nullptr) return -1;
1106 ssize_t ret = 0;
1107 dirent* ent;
1108 while ((ent = readdir(dir)) != nullptr) ret++;
1109 closedir(dir);
1110 return ret;
1111}
1112
Andrei Homescua858b0e2022-08-01 23:43:09 +00001113TEST_P(BinderRpc, Fds) {
1114 if (serverSingleThreaded()) {
1115 GTEST_SKIP() << "This test requires multiple threads";
1116 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001117 if (socketType() == SocketType::TIPC) {
1118 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1119 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001120
Steven Moreland5553ac42020-11-11 02:14:45 +00001121 ssize_t beforeFds = countFds();
1122 ASSERT_GE(beforeFds, 0);
1123 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001124 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001125 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1126 }
1127 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1128}
1129
Andrei Homescud65666d2023-03-03 07:28:02 +00001130#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001131
1132static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1133 std::vector<BinderRpc::ParamType> ret;
1134
1135 for (const auto& clientVersion : testVersions()) {
1136 for (const auto& serverVersion : testVersions()) {
1137 ret.push_back(BinderRpc::ParamType{
1138 .type = SocketType::TIPC,
1139 .security = RpcSecurity::RAW,
1140 .clientVersion = clientVersion,
1141 .serverVersion = serverVersion,
1142 .singleThreaded = true,
1143 .noKernel = true,
1144 });
1145 }
1146 }
1147
1148 return ret;
1149}
1150
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001151INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1152 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001153#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001154bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001155 // We don't need to enable TLS to know if vsock is supported.
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,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001167 .svm_port = VMADDR_PORT_ANY,
Andrei Homescu992a4052022-06-28 21:26:18 +00001168 .svm_cid = VMADDR_CID_ANY,
1169 };
1170 int ret = TEMP_FAILURE_RETRY(
1171 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001172 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
Andrei Homescu992a4052022-06-28 21:26:18 +00001173 strerror(errno));
1174
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001175 socklen_t len = sizeof(serverAddr);
1176 ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
1177 LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
Hannah.Hsu6b1036f2024-07-09 11:20:20 +08001178 LOG_ALWAYS_FATAL_IF(len < static_cast<socklen_t>(sizeof(serverAddr)),
1179 "getsockname didn't read the full addr struct");
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001180
Andrei Homescu992a4052022-06-28 21:26:18 +00001181 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001182 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001183 strerror(errno));
1184
1185 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1186 // to see if the kernel supports it. It's safe to use a blocking
1187 // connect because vsock sockets have a 2 second connection timeout,
1188 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001189 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001190 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001191 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
1192 serverAddr.svm_port, strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001193
1194 bool success = false;
1195 sockaddr_vm connectAddr{
1196 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001197 .svm_port = serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001198 .svm_cid = VMADDR_CID_LOCAL,
1199 };
1200 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1201 sizeof(connectAddr)));
1202 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001203 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001204 while (true) {
1205 pollfd pfd[]{
1206 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1207 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1208 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001209 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001210 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1211
1212 if (pfd[0].revents & POLLIN) {
1213 sockaddr_vm acceptAddr;
1214 socklen_t acceptAddrLen = sizeof(acceptAddr);
1215 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1216 reinterpret_cast<sockaddr*>(&acceptAddr),
1217 &acceptAddrLen, SOCK_CLOEXEC));
1218 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1219 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1220 "Truncated address");
1221
1222 // Store the fd in acceptFd so we keep the connection alive
1223 // while polling connectFd
1224 acceptFd.reset(ret);
1225 }
1226
1227 if (pfd[1].revents & POLLOUT) {
1228 // Connect either succeeded or timed out
1229 int connectErrno;
1230 socklen_t connectErrnoLen = sizeof(connectErrno);
1231 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1232 &connectErrnoLen);
1233 LOG_ALWAYS_FATAL_IF(ret == -1,
1234 "Could not getsockopt() after connect() "
1235 "on non-blocking socket: %s.",
1236 strerror(errno));
1237
1238 // We're done, this is all we wanted
1239 success = connectErrno == 0;
1240 break;
1241 }
1242 }
1243 } else {
1244 success = ret == 0;
1245 }
1246
1247 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1248
1249 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001250}
1251
Yifan Hong1deca4b2021-09-10 16:16:44 -07001252static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001253 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1254 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001255
1256 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001257
Steven Moreland9f250b02023-05-16 23:27:42 +00001258#ifdef __BIONIC__
1259 // Devices may not have vsock support. AVF tests will verify whether they do, but
1260 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001261 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001262#else
1263 // On host machines, we always assume we have vsock loopback. If we don't, the
1264 // subsequent failures will be more clear than showing one now.
1265 static bool hasVsockLoopback = true;
1266#endif
Steven Morelandda573042021-06-12 01:13:45 +00001267
1268 if (hasVsockLoopback) {
1269 ret.push_back(SocketType::VSOCK);
1270 }
1271
1272 return ret;
1273}
1274
Steven Morelandb469f432023-07-28 22:13:47 +00001275static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1276 std::vector<BinderRpc::ParamType> ret;
1277
Steven Morelandf7421432023-07-28 22:41:44 +00001278 constexpr bool full = false;
1279
Steven Morelandb469f432023-07-28 22:13:47 +00001280 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001281 if (full || type == SocketType::UNIX) {
1282 for (const auto& security : RpcSecurityValues()) {
1283 for (const auto& clientVersion : testVersions()) {
1284 for (const auto& serverVersion : testVersions()) {
1285 for (bool singleThreaded : {false, true}) {
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001286 for (bool noKernel : noKernelValues()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001287 ret.push_back(BinderRpc::ParamType{
1288 .type = type,
1289 .security = security,
1290 .clientVersion = clientVersion,
1291 .serverVersion = serverVersion,
1292 .singleThreaded = singleThreaded,
1293 .noKernel = noKernel,
1294 });
1295 }
Steven Morelandb469f432023-07-28 22:13:47 +00001296 }
1297 }
1298 }
1299 }
Steven Morelandf7421432023-07-28 22:41:44 +00001300 } else {
1301 ret.push_back(BinderRpc::ParamType{
1302 .type = type,
1303 .security = RpcSecurity::RAW,
1304 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1305 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1306 .singleThreaded = false,
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001307 .noKernel = !kEnableKernelIpcTesting,
Steven Morelandf7421432023-07-28 22:41:44 +00001308 });
Steven Morelandb469f432023-07-28 22:13:47 +00001309 }
1310 }
Steven Morelandf7421432023-07-28 22:41:44 +00001311
Steven Morelandb469f432023-07-28 22:13:47 +00001312 return ret;
1313}
1314
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001315INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1316 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001317
Yifan Hong702115c2021-06-24 15:39:18 -07001318class BinderRpcServerRootObject
1319 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001320
1321TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1322 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1323 auto setRootObject = [](bool isStrong) -> SetFn {
1324 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1325 };
1326
Yifan Hong702115c2021-06-24 15:39:18 -07001327 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001328 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001329 auto binder1 = sp<BBinder>::make();
1330 IBinder* binderRaw1 = binder1.get();
1331 setRootObject(isStrong1)(server.get(), binder1);
1332 EXPECT_EQ(binderRaw1, server->getRootObject());
1333 binder1.clear();
1334 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1335
1336 auto binder2 = sp<BBinder>::make();
1337 IBinder* binderRaw2 = binder2.get();
1338 setRootObject(isStrong2)(server.get(), binder2);
1339 EXPECT_EQ(binderRaw2, server->getRootObject());
1340 binder2.clear();
1341 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1342}
1343
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001344INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1345 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1346 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001347
Yifan Hong1a235852021-05-13 16:07:47 -07001348class OneOffSignal {
1349public:
1350 // If notify() was previously called, or is called within |duration|, return true; else false.
1351 template <typename R, typename P>
1352 bool wait(std::chrono::duration<R, P> duration) {
1353 std::unique_lock<std::mutex> lock(mMutex);
1354 return mCv.wait_for(lock, duration, [this] { return mValue; });
1355 }
1356 void notify() {
1357 std::unique_lock<std::mutex> lock(mMutex);
1358 mValue = true;
1359 lock.unlock();
1360 mCv.notify_all();
1361 }
1362
1363private:
1364 std::mutex mMutex;
1365 std::condition_variable mCv;
1366 bool mValue = false;
1367};
1368
Yifan Hong194acf22021-06-29 18:44:56 -07001369TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001370 bool expectDebuggable = false;
1371#if defined(__ANDROID__)
1372 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1373 android::base::GetProperty("ro.build.type", "") != "user";
1374#else
Yifan Hong194acf22021-06-29 18:44:56 -07001375 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1376 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1377 "to binderHostDeviceTest. Hence, just disable this test on host.";
1378#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001379 if constexpr (!kEnableKernelIpc) {
1380 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1381 "at build time.";
1382 }
1383
Yifan Hong194acf22021-06-29 18:44:56 -07001384 sp<IServiceManager> sm = defaultServiceManager();
1385 ASSERT_NE(nullptr, sm);
1386 // Any Java service with non-empty getInterfaceDescriptor() would do.
1387 // Let's pick batteryproperties.
1388 auto binder = sm->checkService(String16("batteryproperties"));
1389 ASSERT_NE(nullptr, binder);
1390 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001391 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001392 ASSERT_EQ(OK, binder->pingBinder());
1393
1394 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001395 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001396 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001397 auto socket = rpcServer->releaseServer();
1398
1399 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001400 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1401
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001402 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001403 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001404 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1405 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001406 << statusToString(setRpcClientDebugStatus);
1407 GTEST_SKIP();
1408 }
1409
1410 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001411
1412 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001413 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001414 auto rpcBinder = rpcSession->getRootObject();
1415 ASSERT_NE(nullptr, rpcBinder);
1416
1417 ASSERT_EQ(OK, rpcBinder->pingBinder());
1418
1419 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1420 << "getInterfaceDescriptor should not crash system_server";
1421 ASSERT_EQ(OK, rpcBinder->pingBinder());
1422}
1423
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001424class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1425public:
1426 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001427 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001428 std::to_string(std::get<1>(info.param));
1429 }
1430};
1431
1432TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001433 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001434 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001435 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001436 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001437 ASSERT_FALSE(server->hasServer());
1438 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1439 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001440 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001441 ASSERT_FALSE(server->hasServer());
1442 ASSERT_EQ(sinkFd, retrieved.get());
1443}
1444
1445TEST_P(BinderRpcServerOnly, Shutdown) {
1446 if constexpr (!kEnableRpcThreads) {
1447 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1448 }
1449
1450 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001451 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001452 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001453 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1454 auto joinEnds = std::make_shared<OneOffSignal>();
1455
1456 // If things are broken and the thread never stops, don't block other tests. Because the thread
1457 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1458 // shared pointers are passed.
1459 std::thread([server, joinEnds] {
1460 server->join();
1461 joinEnds->notify();
1462 }).detach();
1463
1464 bool shutdown = false;
1465 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001466 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001467 if (server->shutdown()) shutdown = true;
1468 }
1469 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1470
1471 ASSERT_TRUE(joinEnds->wait(2s))
1472 << "After server->shutdown() returns true, join() did not stop after 2s";
1473}
1474
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001475INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1476 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1477 ::testing::ValuesIn(testVersions())),
1478 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001479
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001480class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001481public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001482 // Only parameterized only server version because `RpcSession` is bypassed
1483 // in the client half of the tests.
1484 using Param =
1485 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001486 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001487
1488 // A server that handles client socket connections.
1489 class Server {
1490 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001491 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001492
Yifan Hong1deca4b2021-09-10 16:16:44 -07001493 explicit Server() {}
1494 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001495 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001496 [[nodiscard]] AssertionResult setUp(
1497 const Param& param,
1498 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001499 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001500 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001501 if (!rpcServer->setProtocolVersion(serverVersion)) {
1502 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1503 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001504 switch (socketType) {
1505 case SocketType::PRECONNECTED: {
1506 return AssertionFailure() << "Not supported by this test";
1507 } break;
1508 case SocketType::UNIX: {
1509 auto addr = allocateSocketAddress();
1510 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1511 if (status != OK) {
1512 return AssertionFailure()
1513 << "setupUnixDomainServer: " << statusToString(status);
1514 }
1515 mConnectToServer = [addr] {
1516 return connectTo(UnixSocketAddress(addr.c_str()));
1517 };
1518 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001519 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001520 unique_fd bootstrapFdClient, bootstrapFdServer;
1521 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001522 return AssertionFailure() << "Socketpair() failed";
1523 }
1524 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1525 std::move(bootstrapFdServer));
1526 if (status != OK) {
1527 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1528 << statusToString(status);
1529 }
1530 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1531 mAcceptConnection = &Server::recvmsgServerConnection;
1532 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1533 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001534 case SocketType::UNIX_RAW: {
1535 auto addr = allocateSocketAddress();
1536 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1537 if (status != OK) {
1538 return AssertionFailure()
1539 << "setupRawSocketServer: " << statusToString(status);
1540 }
1541 mConnectToServer = [addr] {
1542 return connectTo(UnixSocketAddress(addr.c_str()));
1543 };
1544 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001545 case SocketType::VSOCK: {
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001546 unsigned port;
1547 auto status =
1548 rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 if (status != OK) {
1550 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1551 }
1552 mConnectToServer = [port] {
1553 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1554 };
1555 } break;
1556 case SocketType::INET: {
1557 unsigned int port;
1558 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1559 if (status != OK) {
1560 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1561 }
1562 mConnectToServer = [port] {
1563 const char* addr = kLocalInetAddress;
1564 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001565 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001566 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1567 auto fd = connectTo(
1568 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1569 if (fd.ok()) return fd;
1570 }
1571 ALOGE("None of the socket address resolved for %s:%u can be connected",
1572 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001573 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001574 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001575 } break;
1576 case SocketType::TIPC: {
1577 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1578 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001579 }
1580 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001581 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001582 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001583 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1584 mSetup = true;
1585 return AssertionSuccess();
1586 }
1587 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1588 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1589 return mCertVerifier;
1590 }
1591 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1592 void start() {
1593 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1594 mThread = std::make_unique<std::thread>(&Server::run, this);
1595 }
David Brazdil21c887c2022-09-23 12:25:18 +01001596
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001597 unique_fd acceptServerConnection() {
1598 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001599 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1600 }
1601
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001602 unique_fd recvmsgServerConnection() {
1603 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001604 int buf;
1605 iovec iov{&buf, sizeof(buf)};
1606
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001607 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001608 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001609 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001610 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1611 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001612 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001613 }
1614
Yifan Hong1deca4b2021-09-10 16:16:44 -07001615 void run() {
1616 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1617
1618 std::vector<std::thread> threads;
1619 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001620 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1622 }
1623
1624 for (auto& thread : threads) thread.join();
1625 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001626 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001627 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001628 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001629 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001631 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001632 }
Yifan Honge07d2732021-09-13 21:59:14 -07001633 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001634 shutdown();
1635 join();
1636 }
1637 void shutdown() { mFdTrigger->trigger(); }
1638
1639 void setPostConnect(
1640 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1641 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 }
1643
1644 private:
1645 std::unique_ptr<std::thread> mThread;
1646 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001647 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001648 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001649 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001650 std::unique_ptr<RpcTransportCtx> mCtx;
1651 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1652 std::make_shared<RpcCertificateVerifierSimple>();
1653 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001654 // The function invoked after connection and handshake. By default, it is
1655 // |defaultPostConnect| that sends |kMessage| to the client.
1656 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1657 Server::defaultPostConnect;
1658
1659 void join() {
1660 if (mThread != nullptr) {
1661 mThread->join();
1662 mThread = nullptr;
1663 }
1664 }
1665
1666 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1667 FdTrigger* fdTrigger) {
1668 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001669 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001670 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001671 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001672 if (status != OK) return AssertionFailure() << statusToString(status);
1673 return AssertionSuccess();
1674 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001675 };
1676
1677 class Client {
1678 public:
1679 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1680 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001681 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001682 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1683 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001684 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001685 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001686 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1687 return AssertionSuccess();
1688 }
1689 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1690 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1691 return mCertVerifier;
1692 }
Yifan Hong67519322021-09-13 18:51:16 -07001693 // connect() and do handshake
1694 bool setUpTransport() {
1695 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001696 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001697 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1698 return mClientTransport != nullptr;
1699 }
1700 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1701 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1702 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001703 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001704 status_t readStatus =
1705 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001706 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001707 if (readStatus != OK) {
1708 return AssertionFailure() << statusToString(readStatus);
1709 }
1710 if (readMessage != expectedMessage) {
1711 return AssertionFailure()
1712 << "Expected " << expectedMessage << ", actual " << readMessage;
1713 }
1714 return AssertionSuccess();
1715 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001717 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1719 return;
1720 }
1721 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001722 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 }
1724
Pawan49d74cb2022-08-03 21:19:11 +00001725 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1726
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 private:
1728 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001729 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1731 std::unique_ptr<RpcTransportCtx> mCtx;
1732 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1733 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001734 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735 };
1736
1737 // Make A trust B.
1738 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001739 static status_t trust(RpcSecurity rpcSecurity,
1740 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1741 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001742 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001743 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1744 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1745 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001746 }
1747
1748 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001749};
1750
1751class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1752public:
1753 using Server = RpcTransportTestUtils::Server;
1754 using Client = RpcTransportTestUtils::Client;
1755 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001756 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001757 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001758 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001759 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001760 return ret;
1761 }
1762 static std::vector<ParamType> getRpcTranportTestParams() {
1763 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001764 for (auto serverVersion : testVersions()) {
1765 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1766 for (auto rpcSecurity : RpcSecurityValues()) {
1767 switch (rpcSecurity) {
1768 case RpcSecurity::RAW: {
1769 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1770 } break;
1771 case RpcSecurity::TLS: {
1772 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1773 serverVersion);
1774 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1775 serverVersion);
1776 } break;
1777 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001778 }
1779 }
1780 }
1781 return ret;
1782 }
1783 template <typename A, typename B>
1784 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001785 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1786 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001787 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1788 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001789 void SetUp() override {
1790 if constexpr (!kEnableRpcThreads) {
1791 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1792 }
1793 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794};
1795
1796TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001797 auto server = std::make_unique<Server>();
1798 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001799
1800 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001801 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001802
1803 ASSERT_EQ(OK, trust(&client, server));
1804 ASSERT_EQ(OK, trust(server, &client));
1805
1806 server->start();
1807 client.run();
1808}
1809
1810TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001811 auto server = std::make_unique<Server>();
1812 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001813
1814 std::vector<Client> clients;
1815 for (int i = 0; i < 2; i++) {
1816 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001817 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001818 ASSERT_EQ(OK, trust(&client, server));
1819 ASSERT_EQ(OK, trust(server, &client));
1820 }
1821
1822 server->start();
1823 for (auto& client : clients) client.run();
1824}
1825
1826TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001827 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1828 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001830 auto untrustedServer = std::make_unique<Server>();
1831 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001832
1833 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001834 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001835
1836 ASSERT_EQ(OK, trust(untrustedServer, &client));
1837
1838 untrustedServer->start();
1839
1840 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1841 // the client can't verify the server's identity.
1842 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1843 client.run(handshakeOk);
1844}
1845TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001846 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1847 (void)serverVersion;
1848
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 auto validServer = std::make_unique<Server>();
1850 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001851
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001852 auto maliciousServer = std::make_unique<Server>();
1853 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001854
1855 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001856 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001857
1858 ASSERT_EQ(OK, trust(&client, validServer));
1859 ASSERT_EQ(OK, trust(validServer, &client));
1860 ASSERT_EQ(OK, trust(maliciousServer, &client));
1861
1862 maliciousServer->start();
1863
1864 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1865 // the client can't verify the server's identity.
1866 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1867 client.run(handshakeOk);
1868}
1869
1870TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001871 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1872 (void)serverVersion;
1873
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001874 auto server = std::make_unique<Server>();
1875 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001876
1877 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001878 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001879
1880 ASSERT_EQ(OK, trust(&client, server));
1881
1882 server->start();
1883
1884 // For TLS, Client should be able to verify server's identity, so client should see
1885 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1886 // identity and should drop the connection, so client shouldn't be able to read anything.
1887 bool readOk = rpcSecurity != RpcSecurity::TLS;
1888 client.run(true, readOk);
1889}
1890
1891TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001892 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1893 (void)serverVersion;
1894
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001895 auto server = std::make_unique<Server>();
1896 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001897
1898 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001899 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001900 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001901 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902
1903 ASSERT_EQ(OK, trust(&validClient, server));
1904 ASSERT_EQ(OK, trust(&maliciousClient, server));
1905
1906 server->start();
1907
1908 // See UntrustedClient.
1909 bool readOk = rpcSecurity != RpcSecurity::TLS;
1910 maliciousClient.run(true, readOk);
1911}
1912
Yifan Hong67519322021-09-13 18:51:16 -07001913TEST_P(RpcTransportTest, Trigger) {
1914 std::string msg2 = ", world!";
1915 std::mutex writeMutex;
1916 std::condition_variable writeCv;
1917 bool shouldContinueWriting = false;
1918 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001919 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001920 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001921 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1922 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001923 if (status != OK) return AssertionFailure() << statusToString(status);
1924
1925 {
1926 std::unique_lock<std::mutex> lock(writeMutex);
1927 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1928 return AssertionFailure() << "write barrier not cleared in time!";
1929 }
1930 }
1931
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001932 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001933 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1934 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001935 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001936 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001937 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001938 << statusToString(status);
1939 return AssertionSuccess();
1940 };
1941
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001942 auto server = std::make_unique<Server>();
1943 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001944
1945 // Set up client
1946 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001947 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001948
1949 // Exchange keys
1950 ASSERT_EQ(OK, trust(&client, server));
1951 ASSERT_EQ(OK, trust(server, &client));
1952
1953 server->setPostConnect(serverPostConnect);
1954
Yifan Hong67519322021-09-13 18:51:16 -07001955 server->start();
1956 // connect() to server and do handshake
1957 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001958 // read the first message. This ensures that server has finished handshake and start handling
1959 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001960 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001961 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1962 // write is on an FdTrigger that has been shut down.
1963 server->shutdown();
1964 // Continues server thread to write the second message.
1965 {
Yifan Hong22211f82021-09-14 12:32:25 -07001966 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001967 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001968 }
Yifan Hong22211f82021-09-14 12:32:25 -07001969 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001970 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001971 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001972 // On the client side, second read fails with DEAD_OBJECT
1973 ASSERT_FALSE(client.readMessage(msg2));
1974}
1975
Pawan49d74cb2022-08-03 21:19:11 +00001976TEST_P(RpcTransportTest, CheckWaitingForRead) {
1977 std::mutex readMutex;
1978 std::condition_variable readCv;
1979 bool shouldContinueReading = false;
1980 // Server will write data on transport once its started
1981 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1982 std::string message(RpcTransportTestUtils::kMessage);
1983 iovec messageIov{message.data(), message.size()};
1984 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1985 std::nullopt, nullptr);
1986 if (status != OK) return AssertionFailure() << statusToString(status);
1987
1988 {
1989 std::unique_lock<std::mutex> lock(readMutex);
1990 shouldContinueReading = true;
1991 lock.unlock();
1992 readCv.notify_all();
1993 }
1994 return AssertionSuccess();
1995 };
1996
1997 // Setup Server and client
1998 auto server = std::make_unique<Server>();
1999 ASSERT_TRUE(server->setUp(GetParam()));
2000
2001 Client client(server->getConnectToServerFn());
2002 ASSERT_TRUE(client.setUp(GetParam()));
2003
2004 ASSERT_EQ(OK, trust(&client, server));
2005 ASSERT_EQ(OK, trust(server, &client));
2006 server->setPostConnect(serverPostConnect);
2007
2008 server->start();
2009 ASSERT_TRUE(client.setUpTransport());
2010 {
2011 // Wait till server writes data
2012 std::unique_lock<std::mutex> lock(readMutex);
2013 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2014 }
2015
2016 // Since there is no read polling here, we will get polling count 0
2017 ASSERT_FALSE(client.isTransportWaiting());
2018 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2019 // Thread should increment polling count, read and decrement polling count
2020 // Again, polling count should be zero here
2021 ASSERT_FALSE(client.isTransportWaiting());
2022
2023 server->shutdown();
2024}
2025
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002026INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2027 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2028 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002029
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002030class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002031 : public testing::TestWithParam<
2032 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002033public:
2034 template <typename A, typename B>
2035 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002036 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2037 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002038 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2039 }
2040 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002041 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2042 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2043 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002044 };
2045};
2046
2047TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002048 if constexpr (!kEnableRpcThreads) {
2049 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2050 }
2051
Frederick Mayledc07cf82022-05-26 20:30:12 +00002052 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002053
2054 std::vector<uint8_t> pkeyData, certData;
2055 {
2056 auto pkey = makeKeyPairForSelfSignedCert();
2057 ASSERT_NE(nullptr, pkey);
2058 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2059 ASSERT_NE(nullptr, cert);
2060 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2061 certData = serializeCertificate(cert.get(), certificateFormat);
2062 }
2063
2064 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2065 auto desCert = deserializeCertificate(certData, certificateFormat);
2066 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002067 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2068 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002069
2070 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2071 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2072
2073 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2074 ASSERT_TRUE(client.setUp(utilsParam));
2075
2076 ASSERT_EQ(OK, trust(&client, server));
2077 ASSERT_EQ(OK, trust(server, &client));
2078
2079 server->start();
2080 client.run();
2081}
2082
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002083INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002084 BinderRpc, RpcTransportTlsKeyTest,
2085 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2086 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002087 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2088 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002089 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002090#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002091
Steven Morelandc1635952021-04-01 16:20:47 +00002092} // namespace android
2093
2094int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002095 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002096 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002097
Steven Moreland5553ac42020-11-11 02:14:45 +00002098 return RUN_ALL_TESTS();
2099}