blob: 506fc716cdf565e1fde48b5df442608a184d67bd [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
Devin Moorec370db42024-08-09 23:18:05 +000049// TODO need to add IServiceManager.cpp/.h to libbinder_no_kernel
50#ifdef BINDER_WITH_KERNEL_IPC
51#include "android-base/logging.h"
52#include "android/binder_manager.h"
53#include "android/binder_rpc.h"
54#endif // BINDER_WITH_KERNEL_IPC
55
Yifan Hong1a235852021-05-13 16:07:47 -070056using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070057using namespace std::placeholders;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070058using android::binder::borrowed_fd;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -070059using android::binder::GetExecutableDirectory;
60using android::binder::ReadFdToString;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070061using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070062using testing::AssertionFailure;
63using testing::AssertionResult;
64using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070065
Steven Moreland5553ac42020-11-11 02:14:45 +000066namespace android {
67
Andrei Homescu12106de2022-04-27 04:42:21 +000068#ifdef BINDER_TEST_NO_SHARED_LIBS
69constexpr bool kEnableSharedLibs = false;
70#else
71constexpr bool kEnableSharedLibs = true;
72#endif
73
Andrei Homescud65666d2023-03-03 07:28:02 +000074#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000075constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
76#endif
77
Devin Moore0555fbf2024-08-29 15:51:50 +000078constexpr char kKnownAidlService[] = "activity";
79
Frederick Maylea12b0962022-06-25 01:13:22 +000080static std::string WaitStatusToString(int wstatus) {
81 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070082 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000083 }
84 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070085 return "term signal " + std::to_string(WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000086 }
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070087 return "unexpected state " + std::to_string(wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000088}
89
Steven Moreland276d8df2022-09-28 23:56:39 +000090static void debugBacktrace(pid_t pid) {
91 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
92 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
93}
94
Steven Moreland5553ac42020-11-11 02:14:45 +000095class Process {
96public:
Andrei Homescu96834632022-10-14 00:49:49 +000097 Process(Process&& other)
98 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
99 mReadEnd(std::move(other.mReadEnd)),
100 mWriteEnd(std::move(other.mWriteEnd)) {
101 // The default move constructor doesn't clear mPid after moving it,
102 // which we need to do because the destructor checks for mPid!=0
103 mPid = other.mPid;
104 other.mPid = 0;
105 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700106 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
107 unique_fd childWriteEnd;
108 unique_fd childReadEnd;
109 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
110 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +0000111 if (0 == (mPid = fork())) {
112 // racey: assume parent doesn't crash before this is set
113 prctl(PR_SET_PDEATHSIG, SIGHUP);
114
Yifan Hong1deca4b2021-09-10 16:16:44 -0700115 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000116
117 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 }
119 }
120 ~Process() {
121 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000122 int wstatus;
123 waitpid(mPid, &wstatus, 0);
124 if (mCustomExitStatusCheck) {
125 mCustomExitStatusCheck(wstatus);
126 } else {
127 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
128 << "server process failed: " << WaitStatusToString(wstatus);
129 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000130 }
131 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700132 borrowed_fd readEnd() { return mReadEnd; }
133 borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000134
Frederick Maylea12b0962022-06-25 01:13:22 +0000135 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
136 mCustomExitStatusCheck = std::move(f);
137 }
138
Frederick Mayle69a0c992022-05-26 20:38:39 +0000139 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
140 void terminate() { kill(mPid, SIGTERM); }
141
Steven Moreland276d8df2022-09-28 23:56:39 +0000142 pid_t getPid() { return mPid; }
143
Steven Moreland5553ac42020-11-11 02:14:45 +0000144private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000145 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000146 pid_t mPid = 0;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700147 unique_fd mReadEnd;
148 unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000149};
150
151static std::string allocateSocketAddress() {
152 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000153 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000154 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700155 unlink(ret.c_str());
156 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000157};
158
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700159static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000160 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700161 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700162 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
163 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
164 PLOGF("initUnixSocket failed to bind");
165 }
Alice Wang893a9912022-10-24 10:44:09 +0000166 return fd;
167}
168
Andrei Homescu96834632022-10-14 00:49:49 +0000169// Destructors need to be defined, even if pure virtual
170ProcessSession::~ProcessSession() {}
171
172class LinuxProcessSession : public ProcessSession {
173public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000174 // reference to process hosting a socket server
175 Process host;
176
Andrei Homescu96834632022-10-14 00:49:49 +0000177 LinuxProcessSession(LinuxProcessSession&&) = default;
178 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
179 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 for (auto& session : sessions) {
181 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000182 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000183
Steven Moreland67f85902023-03-15 01:13:49 +0000184 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
185 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000187
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188 EXPECT_NE(nullptr, session);
189 EXPECT_NE(nullptr, session->state());
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700190 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000191
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192 wp<RpcSession> weakSession = session;
193 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000194
Steven Moreland57042712022-10-04 23:56:45 +0000195 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
196 // the object should not actually be promotable. By looping, we distinguish a race here
197 // from a bug causing the object to not be promotable.
198 for (size_t i = 0; i < 3; i++) {
199 sp<RpcSession> strongSession = weakSession.promote();
200 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000201 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000202 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
203 "Leaked sess: ")
204 << strongSession->getStrongCount() << " checked time " << i;
205
206 if (strongSession != nullptr) {
207 sleep(1);
208 }
209 }
Steven Moreland736664b2021-05-01 04:27:25 +0000210 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000211 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000212
Andrei Homescu96834632022-10-14 00:49:49 +0000213 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
214 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000215 }
Andrei Homescu96834632022-10-14 00:49:49 +0000216
217 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000218};
219
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700220static unique_fd connectTo(const RpcSocketAddress& addr) {
221 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700222 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700223 if (!serverFd.ok()) {
224 PLOGF("Could not create socket %s", addr.toString().c_str());
225 }
Steven Moreland4198a122021-08-03 17:37:58 -0700226
227 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700228 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700229 }
230 return serverFd;
231}
232
Andrei Homescud65666d2023-03-03 07:28:02 +0000233#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700234static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
235 unique_fd sockClient, sockServer;
236 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700237 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100238 }
239
240 int zero = 0;
241 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700242 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100243 fds.emplace_back(std::move(sockServer));
244
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000245 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700246 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100247 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700248 return sockClient;
David Brazdil21c887c2022-09-23 12:25:18 +0100249}
Andrei Homescud65666d2023-03-03 07:28:02 +0000250#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100251
Andrei Homescuf30148c2023-03-10 00:31:45 +0000252std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
253 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000254}
Andrei Homescu2a298012022-06-15 01:08:54 +0000255
Andrei Homescu96834632022-10-14 00:49:49 +0000256// This creates a new process serving an interface on a certain number of
257// threads.
258std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
259 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700260 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000261
Steven Moreland67f85902023-03-15 01:13:49 +0000262 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700263 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
264 "%s: %zu != %zu", __func__,
265 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000266 }
267
Steven Morelandb469f432023-07-28 22:13:47 +0000268 SocketType socketType = GetParam().type;
269 RpcSecurity rpcSecurity = GetParam().security;
270 uint32_t clientVersion = GetParam().clientVersion;
271 uint32_t serverVersion = GetParam().serverVersion;
272 bool singleThreaded = GetParam().singleThreaded;
273 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000274
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700275 std::string path = GetExecutableDirectory();
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -0700276 auto servicePath = path + "/binder_rpc_test_service" +
Devin Moore1df9c5f2024-07-23 22:09:29 +0000277 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "") +
278 TEST_FILE_SUFFIX;
Andrei Homescu96834632022-10-14 00:49:49 +0000279
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700280 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000281
Alice Wang893a9912022-10-24 10:44:09 +0000282 auto addr = allocateSocketAddress();
283 // Initializes the socket before the fork/exec.
284 if (socketType == SocketType::UNIX_RAW) {
285 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000286 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
287 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
288 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700289 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700290 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000291 }
Alice Wang893a9912022-10-24 10:44:09 +0000292 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000293
Andrei Homescu96834632022-10-14 00:49:49 +0000294 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700295 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000296 if (socketType == SocketType::TIPC) {
297 // Trusty has a single persistent service
298 return;
299 }
300
Andrei Homescu96834632022-10-14 00:49:49 +0000301 auto writeFd = std::to_string(writeEnd.get());
302 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800303 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
304 readFd.c_str(), NULL);
305 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
306 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000307 }));
308
309 BinderRpcTestServerConfig serverConfig;
310 serverConfig.numThreads = options.numThreads;
311 serverConfig.socketType = static_cast<int32_t>(socketType);
312 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
313 serverConfig.serverVersion = serverVersion;
Alice Wang893a9912022-10-24 10:44:09 +0000314 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000315 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000316 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
317 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
318 static_cast<int32_t>(mode));
319 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000320 if (socketType != SocketType::TIPC) {
321 writeToFd(ret->host.writeEnd(), serverConfig);
322 }
Andrei Homescu96834632022-10-14 00:49:49 +0000323
324 std::vector<sp<RpcSession>> sessions;
325 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
326 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000327 std::unique_ptr<RpcTransportCtxFactory> factory;
328 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000329#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000330 factory = RpcTransportCtxFactoryTipcAndroid::make();
331#else
332 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
333#endif
334 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000335 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000336 }
337 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100338 }
339
Andrei Homescu68a55612022-08-02 01:25:15 +0000340 BinderRpcTestServerInfo serverInfo;
341 if (socketType != SocketType::TIPC) {
342 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
343 BinderRpcTestClientInfo clientInfo;
344 for (const auto& session : sessions) {
345 auto& parcelableCert = clientInfo.certs.emplace_back();
346 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
347 }
348 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000349
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700350 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000351 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700352 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000353 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000354
Andrei Homescu68a55612022-08-02 01:25:15 +0000355 if (rpcSecurity == RpcSecurity::TLS) {
356 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700357 LOG_ALWAYS_FATAL_IF(
358 OK !=
359 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000360 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700361 }
362
Andrei Homescu96834632022-10-14 00:49:49 +0000363 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000364
Steven Moreland67f85902023-03-15 01:13:49 +0000365 for (size_t i = 0; i < sessions.size(); i++) {
366 const auto& session = sessions.at(i);
367
368 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
369 ? options.numIncomingConnectionsBySession.at(i)
370 : 0;
371
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700372 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000373 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000374 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000375 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000376
Devin Moore18f63752024-08-08 21:01:24 +0000377 sockaddr_storage addr{};
378 socklen_t addrLen = 0;
379
Andrei Homescu96834632022-10-14 00:49:49 +0000380 switch (socketType) {
Devin Moore18f63752024-08-08 21:01:24 +0000381 case SocketType::PRECONNECTED: {
382 sockaddr_un addr_un{};
383 addr_un.sun_family = AF_UNIX;
384 strcpy(addr_un.sun_path, serverConfig.addr.c_str());
385 addr = *reinterpret_cast<sockaddr_storage*>(&addr_un);
386 addrLen = sizeof(sockaddr_un);
387
Andrei Homescu96834632022-10-14 00:49:49 +0000388 status = session->setupPreconnectedClient({}, [=]() {
389 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
390 });
Devin Moore18f63752024-08-08 21:01:24 +0000391 } break;
Alice Wang893a9912022-10-24 10:44:09 +0000392 case SocketType::UNIX_RAW:
Devin Moore18f63752024-08-08 21:01:24 +0000393 case SocketType::UNIX: {
394 sockaddr_un addr_un{};
395 addr_un.sun_family = AF_UNIX;
396 strcpy(addr_un.sun_path, serverConfig.addr.c_str());
397 addr = *reinterpret_cast<sockaddr_storage*>(&addr_un);
398 addrLen = sizeof(sockaddr_un);
399
Andrei Homescu96834632022-10-14 00:49:49 +0000400 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Devin Moore18f63752024-08-08 21:01:24 +0000401 } break;
Andrei Homescu96834632022-10-14 00:49:49 +0000402 case SocketType::UNIX_BOOTSTRAP:
403 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700404 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000405 break;
Devin Moore18f63752024-08-08 21:01:24 +0000406 case SocketType::VSOCK: {
407 sockaddr_vm addr_vm{
408 .svm_family = AF_VSOCK,
409 .svm_port = static_cast<unsigned int>(serverInfo.port),
410 .svm_cid = VMADDR_CID_LOCAL,
411 };
412 addr = *reinterpret_cast<sockaddr_storage*>(&addr_vm);
413 addrLen = sizeof(sockaddr_vm);
414
Tomasz Wasilczyk022db682024-06-17 13:55:51 -0700415 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverInfo.port);
Devin Moore18f63752024-08-08 21:01:24 +0000416 } break;
417 case SocketType::INET: {
418 const std::string ip_addr = "127.0.0.1";
419 sockaddr_in addr_in{};
420 addr_in.sin_family = AF_INET;
421 addr_in.sin_port = htons(serverInfo.port);
422 inet_aton(ip_addr.c_str(), &addr_in.sin_addr);
423 addr = *reinterpret_cast<sockaddr_storage*>(&addr_in);
424 addrLen = sizeof(sockaddr_in);
425
426 status = session->setupInetClient(ip_addr.c_str(), serverInfo.port);
427 } break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000428 case SocketType::TIPC:
429 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000430#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000431 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000432 for (size_t i = 0; i < 5; i++) {
433 // Try to connect several times,
434 // in case the service is slow to start
435 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
436 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700437 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000438 }
439 usleep(50000);
440 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700441 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000442#else
443 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700444 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000445#endif
446 });
447 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000448 default:
449 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000450 }
Andrei Homescu96834632022-10-14 00:49:49 +0000451 if (options.allowConnectFailure && status != OK) {
452 ret->sessions.clear();
453 break;
454 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700455 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Devin Moore18f63752024-08-08 21:01:24 +0000456 ret->sessions.push_back({session, session->getRootObject(), addr, addrLen});
Steven Morelandc1635952021-04-01 16:20:47 +0000457 }
Andrei Homescu96834632022-10-14 00:49:49 +0000458 return ret;
459}
Steven Morelandc1635952021-04-01 16:20:47 +0000460
Andrei Homescua858b0e2022-08-01 23:43:09 +0000461TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
462 if (clientOrServerSingleThreaded()) {
463 GTEST_SKIP() << "This test requires multiple threads";
464 }
465
Steven Moreland51cdc2c2024-09-17 17:21:27 +0000466 constexpr size_t kNumThreads = 5;
Steven Moreland5553ac42020-11-11 02:14:45 +0000467
Steven Moreland4313d7e2021-07-15 23:41:22 +0000468 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000469
470 EXPECT_OK(proc.rootIface->lock());
471
472 // block all but one thread taking locks
473 std::vector<std::thread> ts;
474 for (size_t i = 0; i < kNumThreads - 1; i++) {
475 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
476 }
477
Steven Morelandd6d816f2022-12-23 01:37:17 +0000478 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000479
480 // other calls still work
481 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
482
Steven Morelandd6d816f2022-12-23 01:37:17 +0000483 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000484 size_t epochMsBefore = epochMillis();
485 // after this, we should never see a response within this time
486 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
487
488 // this call should be blocked for blockTimeMs
489 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
490
491 size_t epochMsAfter = epochMillis();
492 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
493
494 for (auto& t : ts) t.join();
495}
496
Steven Moreland27f620a2023-03-06 19:44:36 +0000497static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 size_t epochMsBefore = epochMillis();
499
500 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700501 for (size_t i = 0; i < numCalls; i++) {
502 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 }
504
505 for (auto& t : ts) t.join();
506
507 size_t epochMsAfter = epochMillis();
508
Yifan Hong1f44f982021-10-08 17:16:47 -0700509 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000510
Steven Moreland68e2ee22024-09-18 01:18:48 +0000511 // b/272429574, b/365294257
512 // This flakes too much to test. Parallelization is tested
513 // in ThreadPoolGreaterThanEqualRequested and other tests.
514 // Test to make sure calls are handled in parallel.
515 // EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700516}
517
Andrei Homescua858b0e2022-08-01 23:43:09 +0000518TEST_P(BinderRpc, ThreadPoolOverSaturated) {
519 if (clientOrServerSingleThreaded()) {
520 GTEST_SKIP() << "This test requires multiple threads";
521 }
522
Yifan Hong1f44f982021-10-08 17:16:47 -0700523 constexpr size_t kNumThreads = 10;
524 constexpr size_t kNumCalls = kNumThreads + 3;
525 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000526
Steven Moreland68e2ee22024-09-18 01:18:48 +0000527 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 200 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700528}
529
Andrei Homescua858b0e2022-08-01 23:43:09 +0000530TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
531 if (clientOrServerSingleThreaded()) {
532 GTEST_SKIP() << "This test requires multiple threads";
533 }
534
Yifan Hong1f44f982021-10-08 17:16:47 -0700535 constexpr size_t kNumThreads = 20;
536 constexpr size_t kNumOutgoingConnections = 10;
537 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
538 auto proc = createRpcTestSocketServerProcess(
539 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000540
Steven Moreland68e2ee22024-09-18 01:18:48 +0000541 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 200 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000542}
543
Andrei Homescua858b0e2022-08-01 23:43:09 +0000544TEST_P(BinderRpc, ThreadingStressTest) {
545 if (clientOrServerSingleThreaded()) {
546 GTEST_SKIP() << "This test requires multiple threads";
547 }
548
Steven Moreland27f620a2023-03-06 19:44:36 +0000549 constexpr size_t kNumClientThreads = 5;
550 constexpr size_t kNumServerThreads = 5;
551 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000552
Steven Moreland4313d7e2021-07-15 23:41:22 +0000553 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000554
555 std::vector<std::thread> threads;
556 for (size_t i = 0; i < kNumClientThreads; i++) {
557 threads.push_back(std::thread([&] {
558 for (size_t j = 0; j < kNumCalls; j++) {
559 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000560 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 EXPECT_EQ(proc.rootBinder, out);
562 }
563 }));
564 }
565
566 for (auto& t : threads) t.join();
567}
568
Steven Moreland925ba0a2021-09-17 18:06:32 -0700569static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
570 std::vector<std::thread> threads;
571 for (size_t i = 0; i < threadCount; i++) {
572 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
573 }
574 for (auto& t : threads) t.join();
575}
576
Andrei Homescua858b0e2022-08-01 23:43:09 +0000577TEST_P(BinderRpc, OnewayStressTest) {
578 if (clientOrServerSingleThreaded()) {
579 GTEST_SKIP() << "This test requires multiple threads";
580 }
581
Steven Morelandc6046982021-04-20 00:49:42 +0000582 constexpr size_t kNumClientThreads = 10;
583 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700584 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000585
Steven Moreland4313d7e2021-07-15 23:41:22 +0000586 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000587
588 std::vector<std::thread> threads;
589 for (size_t i = 0; i < kNumClientThreads; i++) {
590 threads.push_back(std::thread([&] {
591 for (size_t j = 0; j < kNumCalls; j++) {
592 EXPECT_OK(proc.rootIface->sendString("a"));
593 }
Steven Morelandc6046982021-04-20 00:49:42 +0000594 }));
595 }
596
597 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700598
599 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000600}
601
Frederick Mayleb0221d12022-10-03 23:10:53 +0000602TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
603 if (!supportsFdTransport()) {
604 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
605 }
606 if (clientOrServerSingleThreaded()) {
607 GTEST_SKIP() << "This test requires multiple threads";
608 }
609
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000610 constexpr size_t kNumServerThreads = 3;
611
Frederick Mayleb0221d12022-10-03 23:10:53 +0000612 // This test forces a oneway transaction to be queued by issuing two
613 // `blockingSendFdOneway` calls, then drains the queue by issuing two
614 // `blockingRecvFd` calls.
615 //
616 // For more details about the queuing semantics see
617 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
618
619 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000620 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000621 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
622 .serverSupportedFileDescriptorTransportModes =
623 {RpcSession::FileDescriptorTransportMode::UNIX},
624 });
625
626 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
627 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
628 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
629 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
630
631 android::os::ParcelFileDescriptor fdA;
632 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
633 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700634 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000635 EXPECT_EQ(result, "a");
636
637 android::os::ParcelFileDescriptor fdB;
638 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700639 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000640 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000641
642 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000643}
644
Andrei Homescua858b0e2022-08-01 23:43:09 +0000645TEST_P(BinderRpc, OnewayCallQueueing) {
646 if (clientOrServerSingleThreaded()) {
647 GTEST_SKIP() << "This test requires multiple threads";
648 }
649
Frederick Mayle96872592023-03-07 14:56:15 -0800650 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000651 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
653 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000654 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000655
Frederick Mayle96872592023-03-07 14:56:15 -0800656 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700657 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800658 for (size_t i = 0; i + 1 < kNumQueued; i++) {
659 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000660 }
Frederick Mayle96872592023-03-07 14:56:15 -0800661 for (size_t i = 0; i + 1 < kNumQueued; i++) {
662 int n;
663 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700664 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800665 }
Steven Morelandf5174272021-05-25 00:39:28 +0000666
Steven Moreland925ba0a2021-09-17 18:06:32 -0700667 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000668}
669
Andrei Homescua858b0e2022-08-01 23:43:09 +0000670TEST_P(BinderRpc, OnewayCallExhaustion) {
671 if (clientOrServerSingleThreaded()) {
672 GTEST_SKIP() << "This test requires multiple threads";
673 }
674
Steven Morelandd45be622021-06-04 02:19:37 +0000675 constexpr size_t kNumClients = 2;
676 constexpr size_t kTooLongMs = 1000;
677
Steven Moreland4313d7e2021-07-15 23:41:22 +0000678 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000679
680 // Build up oneway calls on the second session to make sure it terminates
681 // and shuts down. The first session should be unaffected (proc destructor
682 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000683 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000684
685 std::vector<std::thread> threads;
686 for (size_t i = 0; i < kNumClients; i++) {
687 // one of these threads will get stuck queueing a transaction once the
688 // socket fills up, the other will be able to fill up transactions on
689 // this object
690 threads.push_back(std::thread([&] {
691 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
692 }
693 }));
694 }
695 for (auto& t : threads) t.join();
696
697 Status status = iface->sleepMsAsync(kTooLongMs);
698 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
699
Steven Moreland798e0d12021-07-14 23:19:25 +0000700 // now that it has died, wait for the remote session to shutdown
701 std::vector<int32_t> remoteCounts;
702 do {
703 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
704 } while (remoteCounts.size() == kNumClients);
705
Steven Morelandd45be622021-06-04 02:19:37 +0000706 // the second session should be shutdown in the other process by the time we
707 // are able to join above (it'll only be hung up once it finishes processing
708 // any pending commands). We need to erase this session from the record
709 // here, so that the destructor for our session won't check that this
710 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000711 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000712}
713
Steven Moreland67f85902023-03-15 01:13:49 +0000714TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
715 if (clientOrServerSingleThreaded()) {
716 GTEST_SKIP() << "This test requires multiple threads";
717 }
718
719 // session 0 - will check for leaks in destrutor of proc
720 // session 1 - we want to make sure it gets deleted when we drop all references to it
721 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700722 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000723
724 wp<RpcSession> session = proc.proc->sessions.at(1).session;
725
726 // remove all references to the second session
727 proc.proc->sessions.at(1).root = nullptr;
728 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
729
730 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
731 // to drain commands.
732 for (size_t i = 0; i < 100; i++) {
733 usleep(10 * 1000);
734 if (session.promote() == nullptr) break;
735 }
736
737 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000738
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000739 // now that it has died, wait for the remote session to shutdown
740 std::vector<int32_t> remoteCounts;
741 do {
742 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
743 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000744}
745
Devin Moore66d5b7a2022-07-07 21:42:10 +0000746TEST_P(BinderRpc, SingleDeathRecipient) {
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 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
767
768 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
769 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
770 }
771
772 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000773 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000774
775 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000776 // can't do this before checking the death recipient by calling
777 // forceShutdown earlier, because shutdownAndWait will also trigger
778 // a death recipient, but if we had a way to wait for the service
779 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000780 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000781 proc.expectAlreadyShutdown = true;
782}
783
784TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000785 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000786 GTEST_SKIP() << "This test requires multiple threads";
787 }
788 class MyDeathRec : public IBinder::DeathRecipient {
789 public:
790 void binderDied(const wp<IBinder>& /* who */) override {
791 dead = true;
792 mCv.notify_one();
793 }
794 std::mutex mMtx;
795 std::condition_variable mCv;
796 bool dead = false;
797 };
798
799 // Death recipient needs to have an incoming connection to be called
800 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000801 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000802
803 auto dr = sp<MyDeathRec>::make();
804 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
805
806 // Explicitly calling shutDownAndWait will cause the death recipients
807 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000808 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000809
810 std::unique_lock<std::mutex> lock(dr->mMtx);
811 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000812 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000813 }
814 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
815
Andrei Homescu96834632022-10-14 00:49:49 +0000816 proc.proc->terminate();
817 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000818 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
819 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
820 });
821 proc.expectAlreadyShutdown = true;
822}
823
Steven Moreland5ec743f2023-01-18 01:02:06 +0000824TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
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 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000829 class MyDeathRec : public IBinder::DeathRecipient {
830 public:
831 void binderDied(const wp<IBinder>& /* who */) override {}
832 };
833
Steven Moreland67f85902023-03-15 01:13:49 +0000834 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000835
836 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000837 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000838}
839
840TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000841 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000842 GTEST_SKIP() << "This test requires multiple threads";
843 }
844 class MyDeathRec : public IBinder::DeathRecipient {
845 public:
846 void binderDied(const wp<IBinder>& /* who */) override {
847 GTEST_FAIL() << "This should not be called after unlinkToDeath";
848 }
849 };
850
851 // Death recipient needs to have an incoming connection to be called
852 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000853 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000854
855 auto dr = sp<MyDeathRec>::make();
856 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
857 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
858
Steven Moreland67f85902023-03-15 01:13:49 +0000859 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000860}
861
Steven Morelandc1635952021-04-01 16:20:47 +0000862TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000863 if (socketType() == SocketType::TIPC) {
864 // This should work, but Trusty takes too long to restart the service
865 GTEST_SKIP() << "Service death test not supported on Trusty";
866 }
867
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000869 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000870
871 // make sure there is some state during crash
872 // 1. we hold their binder
873 sp<IBinderRpcSession> session;
874 EXPECT_OK(proc.rootIface->openSession("happy", &session));
875 // 2. they hold our binder
876 sp<IBinder> binder = new BBinder();
877 EXPECT_OK(proc.rootIface->holdBinder(binder));
878
879 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
880 << "Do death cleanup: " << doDeathCleanup;
881
Andrei Homescu96834632022-10-14 00:49:49 +0000882 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000883 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
884 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
885 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000886 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000887 }
888}
889
Steven Morelandd7302072021-05-15 01:32:04 +0000890TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000891 // This test only works if the current process shared the internal state of
892 // ProcessState with the service across the call to fork(). Both the static
893 // libraries and libbinder.so have their own separate copies of all the
894 // globals, so the test only works when the test client and service both use
895 // libbinder.so (when using static libraries, even a client and service
896 // using the same kind of static library should have separate copies of the
897 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000898 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000899 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
900 "at build time.";
901 }
902
Steven Moreland4313d7e2021-07-15 23:41:22 +0000903 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000904
Andrei Homescu2a298012022-06-15 01:08:54 +0000905 // we can't allocate IPCThreadState so actually the first time should
906 // succeed :(
907 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000908
909 // second time! we catch the error :)
910 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
911
Andrei Homescu96834632022-10-14 00:49:49 +0000912 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000913 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
914 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
915 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000916 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000917}
918
Frederick Mayle69a0c992022-05-26 20:38:39 +0000919TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000920 if (socketType() == SocketType::TIPC) {
921 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
922 }
923
Frederick Mayle69a0c992022-05-26 20:38:39 +0000924 auto proc = createRpcTestSocketServerProcess({
925 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
926 .serverSupportedFileDescriptorTransportModes =
927 {RpcSession::FileDescriptorTransportMode::UNIX},
928 .allowConnectFailure = true,
929 });
Andrei Homescu96834632022-10-14 00:49:49 +0000930 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
931 proc.proc->terminate();
932 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000933 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
934 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
935 });
936 proc.expectAlreadyShutdown = true;
937}
938
939TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000940 if (socketType() == SocketType::TIPC) {
941 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
942 }
943
Frederick Mayle69a0c992022-05-26 20:38:39 +0000944 auto proc = createRpcTestSocketServerProcess({
945 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
946 .serverSupportedFileDescriptorTransportModes =
947 {RpcSession::FileDescriptorTransportMode::NONE},
948 .allowConnectFailure = true,
949 });
Andrei Homescu96834632022-10-14 00:49:49 +0000950 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
951 proc.proc->terminate();
952 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000953 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
954 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
955 });
956 proc.expectAlreadyShutdown = true;
957}
958
959TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000960 if (socketType() == SocketType::TIPC) {
961 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
962 }
963
Frederick Mayle69a0c992022-05-26 20:38:39 +0000964 auto proc = createRpcTestSocketServerProcess({
965 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
966 .serverSupportedFileDescriptorTransportModes =
967 {RpcSession::FileDescriptorTransportMode::NONE,
968 RpcSession::FileDescriptorTransportMode::UNIX},
969 });
970
971 android::os::ParcelFileDescriptor out;
972 auto status = proc.rootIface->echoAsFile("hello", &out);
973 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
974}
975
976TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000977 if (socketType() == SocketType::TIPC) {
978 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
979 }
980
Frederick Mayle69a0c992022-05-26 20:38:39 +0000981 auto proc = createRpcTestSocketServerProcess({
982 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
983 .serverSupportedFileDescriptorTransportModes =
984 {RpcSession::FileDescriptorTransportMode::UNIX},
985 });
986
987 android::os::ParcelFileDescriptor out;
988 auto status = proc.rootIface->echoAsFile("hello", &out);
989 if (!supportsFdTransport()) {
990 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
991 return;
992 }
993 ASSERT_TRUE(status.isOk()) << status;
994
995 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700996 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700997 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000998}
999
1000TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001001 if (socketType() == SocketType::TIPC) {
1002 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1003 }
1004
Frederick Mayle69a0c992022-05-26 20:38:39 +00001005 auto proc = createRpcTestSocketServerProcess({
1006 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1007 .serverSupportedFileDescriptorTransportModes =
1008 {RpcSession::FileDescriptorTransportMode::UNIX},
1009 });
1010
1011 std::vector<android::os::ParcelFileDescriptor> files;
1012 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1013 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1014 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1015 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1016
1017 android::os::ParcelFileDescriptor out;
1018 auto status = proc.rootIface->concatFiles(files, &out);
1019 if (!supportsFdTransport()) {
1020 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1021 return;
1022 }
1023 ASSERT_TRUE(status.isOk()) << status;
1024
1025 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001026 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001027 EXPECT_EQ(result, "123abcd");
1028}
1029
1030TEST_P(BinderRpc, SendMaxFiles) {
1031 if (!supportsFdTransport()) {
1032 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1033 }
1034
1035 auto proc = createRpcTestSocketServerProcess({
1036 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1037 .serverSupportedFileDescriptorTransportModes =
1038 {RpcSession::FileDescriptorTransportMode::UNIX},
1039 });
1040
1041 std::vector<android::os::ParcelFileDescriptor> files;
1042 for (int i = 0; i < 253; i++) {
1043 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1044 }
1045
1046 android::os::ParcelFileDescriptor out;
1047 auto status = proc.rootIface->concatFiles(files, &out);
1048 ASSERT_TRUE(status.isOk()) << status;
1049
1050 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001051 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001052 EXPECT_EQ(result, std::string(253, 'a'));
1053}
1054
1055TEST_P(BinderRpc, SendTooManyFiles) {
1056 if (!supportsFdTransport()) {
1057 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1058 }
1059
1060 auto proc = createRpcTestSocketServerProcess({
1061 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1062 .serverSupportedFileDescriptorTransportModes =
1063 {RpcSession::FileDescriptorTransportMode::UNIX},
1064 });
1065
1066 std::vector<android::os::ParcelFileDescriptor> files;
1067 for (int i = 0; i < 254; i++) {
1068 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1069 }
1070
1071 android::os::ParcelFileDescriptor out;
1072 auto status = proc.rootIface->concatFiles(files, &out);
1073 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1074}
1075
Andrei Homescufc221502022-10-08 03:51:17 +00001076TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001077 if (socketType() == SocketType::TIPC) {
1078 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1079 }
1080
Andrei Homescufc221502022-10-08 03:51:17 +00001081 auto proc = createRpcTestSocketServerProcess({
1082 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1083 .serverSupportedFileDescriptorTransportModes =
1084 {RpcSession::FileDescriptorTransportMode::UNIX},
1085 });
1086
1087 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1088 ASSERT_NE(badFd, -1);
1089
1090 // Close the file descriptor so it becomes invalid for dup
1091 close(badFd);
1092
1093 Parcel p1;
1094 p1.markForBinder(proc.rootBinder);
1095 p1.writeInt32(3);
1096 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1097
1098 Parcel pRaw;
1099 pRaw.markForBinder(proc.rootBinder);
1100 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1101
1102 pRaw.setDataPosition(0);
1103 EXPECT_EQ(3, pRaw.readInt32());
1104 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1105}
1106
Andrei Homescu68a55612022-08-02 01:25:15 +00001107#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001108TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001109 if constexpr (!kEnableSharedLibs) {
1110 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1111 }
1112
Steven Moreland4313d7e2021-07-15 23:41:22 +00001113 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001114
1115 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1116 ASSERT_NE(binder, nullptr);
1117
1118 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1119}
1120
1121TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001122 if constexpr (!kEnableSharedLibs) {
1123 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1124 }
1125
Steven Moreland4313d7e2021-07-15 23:41:22 +00001126 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001127
1128 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1129 ASSERT_NE(binder, nullptr);
1130
1131 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1132 ASSERT_NE(ndkBinder, nullptr);
1133
1134 std::string out;
1135 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1136 ASSERT_TRUE(status.isOk()) << status.getDescription();
1137 ASSERT_EQ("aoeuaoeu", out);
1138}
Andrei Homescu68a55612022-08-02 01:25:15 +00001139#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001140
Steven Moreland5553ac42020-11-11 02:14:45 +00001141ssize_t countFds() {
1142 DIR* dir = opendir("/proc/self/fd/");
1143 if (dir == nullptr) return -1;
1144 ssize_t ret = 0;
1145 dirent* ent;
1146 while ((ent = readdir(dir)) != nullptr) ret++;
1147 closedir(dir);
1148 return ret;
1149}
1150
Andrei Homescua858b0e2022-08-01 23:43:09 +00001151TEST_P(BinderRpc, Fds) {
1152 if (serverSingleThreaded()) {
1153 GTEST_SKIP() << "This test requires multiple threads";
1154 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001155 if (socketType() == SocketType::TIPC) {
1156 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1157 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001158
Steven Moreland5553ac42020-11-11 02:14:45 +00001159 ssize_t beforeFds = countFds();
1160 ASSERT_GE(beforeFds, 0);
1161 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001162 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001163 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1164 }
1165 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1166}
1167
Devin Moore18f63752024-08-08 21:01:24 +00001168// TODO need to add IServiceManager.cpp/.h to libbinder_no_kernel
1169#ifdef BINDER_WITH_KERNEL_IPC
1170
1171class BinderRpcAccessor : public BinderRpc {
1172 void SetUp() override {
1173 if (serverSingleThreaded()) {
1174 // This blocks on android::FdTrigger::triggerablePoll when attempting to set
1175 // up the client RpcSession
1176 GTEST_SKIP() << "Accessors are not supported for single threaded libbinder";
1177 }
1178 if (rpcSecurity() == RpcSecurity::TLS) {
1179 GTEST_SKIP() << "Accessors are not supported with TLS";
1180 // ... for now
1181 }
1182
1183 if (socketType() == SocketType::UNIX_BOOTSTRAP) {
1184 GTEST_SKIP() << "Accessors do not support UNIX_BOOTSTRAP because no connection "
1185 "information is known";
1186 }
1187 if (socketType() == SocketType::TIPC) {
1188 GTEST_SKIP() << "Accessors do not support TIPC because the socket transport is not "
1189 "known in libbinder";
1190 }
1191 BinderRpc::SetUp();
1192 }
1193};
1194
1195inline void waitForExtraSessionCleanup(const BinderRpcTestProcessSession& proc) {
1196 // Need to give the server some time to delete its RpcSession after our last
1197 // reference is dropped, closing the connection. Check for up to 1 second,
1198 // every 10 ms.
1199 for (size_t i = 0; i < 100; i++) {
1200 std::vector<int32_t> remoteCounts;
1201 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1202 // We exect the original binder to still be alive, we just want to wait
1203 // for this extra session to be cleaned up.
1204 if (remoteCounts.size() == proc.proc->sessions.size()) break;
1205 usleep(10000);
1206 }
1207}
1208
1209TEST_P(BinderRpcAccessor, InjectAndGetServiceHappyPath) {
1210 constexpr size_t kNumThreads = 10;
1211 const String16 kInstanceName("super.cool.service/better_than_default");
1212
1213 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1214 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1215
Devin Moorec370db42024-08-09 23:18:05 +00001216 auto receipt = addAccessorProvider(
1217 {String8(kInstanceName).c_str()}, [&](const String16& name) -> sp<IBinder> {
1218 return createAccessor(name,
1219 [&](const String16& name, sockaddr* outAddr,
1220 socklen_t addrSize) -> status_t {
1221 if (outAddr == nullptr ||
1222 addrSize < proc.proc->sessions[0].addrLen) {
1223 return BAD_VALUE;
1224 }
1225 if (name == kInstanceName) {
1226 if (proc.proc->sessions[0].addr.ss_family ==
1227 AF_UNIX) {
1228 sockaddr_un* un = reinterpret_cast<sockaddr_un*>(
1229 &proc.proc->sessions[0].addr);
1230 ALOGE("inside callback: %s", un->sun_path);
1231 }
1232 std::memcpy(outAddr, &proc.proc->sessions[0].addr,
1233 proc.proc->sessions[0].addrLen);
1234 return OK;
1235 }
1236 return NAME_NOT_FOUND;
1237 });
1238 });
Devin Moore18f63752024-08-08 21:01:24 +00001239
1240 EXPECT_FALSE(receipt.expired());
1241
1242 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1243 sp<IBinderRpcTest> service = checked_interface_cast<IBinderRpcTest>(binder);
1244 EXPECT_NE(service, nullptr);
1245
1246 sp<IBinder> out;
1247 EXPECT_OK(service->repeatBinder(binder, &out));
1248 EXPECT_EQ(binder, out);
1249
1250 out.clear();
1251 binder.clear();
1252 service.clear();
1253
1254 status_t status = removeAccessorProvider(receipt);
1255 EXPECT_EQ(status, OK);
1256
1257 waitForExtraSessionCleanup(proc);
1258}
1259
1260TEST_P(BinderRpcAccessor, InjectNoAccessorProvided) {
1261 const String16 kInstanceName("doesnt_matter_nothing_checks");
1262
1263 bool isProviderDeleted = false;
1264
Devin Moorec370db42024-08-09 23:18:05 +00001265 auto receipt = addAccessorProvider({String8(kInstanceName).c_str()},
1266 [&](const String16&) -> sp<IBinder> { return nullptr; });
Devin Moore18f63752024-08-08 21:01:24 +00001267 EXPECT_FALSE(receipt.expired());
1268
1269 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1270 EXPECT_EQ(binder, nullptr);
1271
1272 status_t status = removeAccessorProvider(receipt);
1273 EXPECT_EQ(status, OK);
1274}
1275
Devin Moorec370db42024-08-09 23:18:05 +00001276TEST_P(BinderRpcAccessor, InjectDuplicateAccessorProvider) {
1277 const String16 kInstanceName("super.cool.service/better_than_default");
1278 const String16 kInstanceName2("super.cool.service/better_than_default2");
1279
1280 auto receipt =
1281 addAccessorProvider({String8(kInstanceName).c_str(), String8(kInstanceName2).c_str()},
1282 [&](const String16&) -> sp<IBinder> { return nullptr; });
1283 EXPECT_FALSE(receipt.expired());
1284 // reject this because it's associated with an already used instance name
1285 auto receipt2 = addAccessorProvider({String8(kInstanceName).c_str()},
1286 [&](const String16&) -> sp<IBinder> { return nullptr; });
1287 EXPECT_TRUE(receipt2.expired());
1288
1289 // the first provider should still be usable
1290 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1291 EXPECT_EQ(binder, nullptr);
1292
1293 status_t status = removeAccessorProvider(receipt);
1294 EXPECT_EQ(status, OK);
1295}
1296
1297TEST_P(BinderRpcAccessor, InjectAccessorProviderNoInstance) {
1298 auto receipt = addAccessorProvider({}, [&](const String16&) -> sp<IBinder> { return nullptr; });
1299 EXPECT_TRUE(receipt.expired());
1300}
1301
Devin Moore18f63752024-08-08 21:01:24 +00001302TEST_P(BinderRpcAccessor, InjectNoSockaddrProvided) {
1303 constexpr size_t kNumThreads = 10;
1304 const String16 kInstanceName("super.cool.service/better_than_default");
1305
1306 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1307 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1308
1309 bool isProviderDeleted = false;
1310 bool isAccessorDeleted = false;
1311
Devin Moorec370db42024-08-09 23:18:05 +00001312 auto receipt = addAccessorProvider({String8(kInstanceName).c_str()},
1313 [&](const String16& name) -> sp<IBinder> {
1314 return createAccessor(name,
1315 [&](const String16&, sockaddr*,
1316 socklen_t) -> status_t {
1317 // don't fill in outAddr
1318 return NAME_NOT_FOUND;
1319 });
1320 });
Devin Moore18f63752024-08-08 21:01:24 +00001321
1322 EXPECT_FALSE(receipt.expired());
1323
1324 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1325 EXPECT_EQ(binder, nullptr);
1326
1327 status_t status = removeAccessorProvider(receipt);
1328 EXPECT_EQ(status, OK);
1329}
1330
Devin Moorec370db42024-08-09 23:18:05 +00001331constexpr const char* kARpcInstance = "some.instance.name.IFoo/default";
1332const char* kARpcSupportedServices[] = {
1333 kARpcInstance,
1334};
1335const uint32_t kARpcNumSupportedServices = 1;
1336
1337struct ConnectionInfoData {
1338 sockaddr_storage addr;
1339 socklen_t len;
1340 bool* isDeleted;
1341 ~ConnectionInfoData() {
1342 if (isDeleted) *isDeleted = true;
1343 }
1344};
1345
1346struct AccessorProviderData {
1347 sockaddr_storage addr;
1348 socklen_t len;
1349 bool* isDeleted;
1350 ~AccessorProviderData() {
1351 if (isDeleted) *isDeleted = true;
1352 }
1353};
1354
1355void accessorProviderDataOnDelete(void* data) {
1356 delete reinterpret_cast<AccessorProviderData*>(data);
1357}
1358void infoProviderDataOnDelete(void* data) {
1359 delete reinterpret_cast<ConnectionInfoData*>(data);
1360}
1361
1362ABinderRpc_ConnectionInfo* infoProvider(const char* instance, void* cookie) {
1363 if (instance == nullptr || cookie == nullptr) return nullptr;
1364 ConnectionInfoData* data = reinterpret_cast<ConnectionInfoData*>(cookie);
1365 return ABinderRpc_ConnectionInfo_new(reinterpret_cast<const sockaddr*>(&data->addr), data->len);
1366}
1367
1368ABinderRpc_Accessor* getAccessor(const char* instance, void* cookie) {
1369 if (instance == nullptr || cookie == nullptr) return nullptr;
1370 if (0 != strcmp(instance, kARpcInstance)) return nullptr;
1371
1372 AccessorProviderData* data = reinterpret_cast<AccessorProviderData*>(cookie);
1373
1374 ConnectionInfoData* info = new ConnectionInfoData{
1375 .addr = data->addr,
1376 .len = data->len,
1377 .isDeleted = nullptr,
1378 };
1379
1380 return ABinderRpc_Accessor_new(instance, infoProvider, info, infoProviderDataOnDelete);
1381}
1382
1383class BinderARpcNdk : public ::testing::Test {};
1384
1385TEST_F(BinderARpcNdk, ARpcProviderNewDelete) {
1386 bool isDeleted = false;
1387
1388 AccessorProviderData* data = new AccessorProviderData{{}, 0, &isDeleted};
1389
1390 ABinderRpc_AccessorProvider* provider =
1391 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1392 kARpcNumSupportedServices, data,
1393 accessorProviderDataOnDelete);
1394
1395 ASSERT_NE(provider, nullptr);
1396 EXPECT_FALSE(isDeleted);
1397
1398 ABinderRpc_unregisterAccessorProvider(provider);
1399
1400 EXPECT_TRUE(isDeleted);
1401}
1402
1403TEST_F(BinderARpcNdk, ARpcProviderDuplicateInstance) {
1404 const char* instance = "some.instance.name.IFoo/default";
1405 const uint32_t numInstances = 2;
1406 const char* instances[numInstances] = {
1407 instance,
1408 "some.other.instance/default",
1409 };
1410
1411 bool isDeleted = false;
1412
1413 AccessorProviderData* data = new AccessorProviderData{{}, 0, &isDeleted};
1414
1415 ABinderRpc_AccessorProvider* provider =
1416 ABinderRpc_registerAccessorProvider(getAccessor, instances, numInstances, data,
1417 accessorProviderDataOnDelete);
1418
1419 ASSERT_NE(provider, nullptr);
1420 EXPECT_FALSE(isDeleted);
1421
1422 const uint32_t numInstances2 = 1;
1423 const char* instances2[numInstances2] = {
1424 instance,
1425 };
1426 bool isDeleted2 = false;
1427 AccessorProviderData* data2 = new AccessorProviderData{{}, 0, &isDeleted2};
1428 ABinderRpc_AccessorProvider* provider2 =
1429 ABinderRpc_registerAccessorProvider(getAccessor, instances2, numInstances2, data2,
1430 accessorProviderDataOnDelete);
1431
1432 EXPECT_EQ(provider2, nullptr);
1433 // If it fails to be registered, the data is still cleaned up with
1434 // accessorProviderDataOnDelete
1435 EXPECT_TRUE(isDeleted2);
1436
1437 ABinderRpc_unregisterAccessorProvider(provider);
1438
1439 EXPECT_TRUE(isDeleted);
1440}
1441
1442TEST_F(BinderARpcNdk, ARpcProviderRegisterNoInstance) {
1443 const uint32_t numInstances = 0;
1444 const char* instances[numInstances] = {};
1445
1446 bool isDeleted = false;
1447 AccessorProviderData* data = new AccessorProviderData{{}, 0, &isDeleted};
1448
1449 ABinderRpc_AccessorProvider* provider =
1450 ABinderRpc_registerAccessorProvider(getAccessor, instances, numInstances, data,
1451 accessorProviderDataOnDelete);
1452 ASSERT_EQ(provider, nullptr);
1453}
1454
1455TEST_F(BinderARpcNdk, ARpcAccessorNewDelete) {
1456 bool isDeleted = false;
1457
1458 ConnectionInfoData* data = new ConnectionInfoData{{}, 0, &isDeleted};
1459
1460 ABinderRpc_Accessor* accessor =
1461 ABinderRpc_Accessor_new("gshoe_service", infoProvider, data, infoProviderDataOnDelete);
1462 ASSERT_NE(accessor, nullptr);
1463 EXPECT_FALSE(isDeleted);
1464
1465 ABinderRpc_Accessor_delete(accessor);
1466 EXPECT_TRUE(isDeleted);
1467}
1468
1469TEST_F(BinderARpcNdk, ARpcConnectionInfoNewDelete) {
1470 sockaddr_vm addr{
1471 .svm_family = AF_VSOCK,
1472 .svm_port = VMADDR_PORT_ANY,
1473 .svm_cid = VMADDR_CID_ANY,
1474 };
1475
1476 ABinderRpc_ConnectionInfo* info =
1477 ABinderRpc_ConnectionInfo_new(reinterpret_cast<sockaddr*>(&addr), sizeof(sockaddr_vm));
1478 EXPECT_NE(info, nullptr);
1479
1480 ABinderRpc_ConnectionInfo_delete(info);
1481}
1482
1483TEST_F(BinderARpcNdk, ARpcAsFromBinderAsBinder) {
1484 bool isDeleted = false;
1485
1486 ConnectionInfoData* data = new ConnectionInfoData{{}, 0, &isDeleted};
1487
1488 ABinderRpc_Accessor* accessor =
1489 ABinderRpc_Accessor_new("gshoe_service", infoProvider, data, infoProviderDataOnDelete);
1490 ASSERT_NE(accessor, nullptr);
1491 EXPECT_FALSE(isDeleted);
1492
1493 {
1494 ndk::SpAIBinder binder = ndk::SpAIBinder(ABinderRpc_Accessor_asBinder(accessor));
1495 EXPECT_NE(binder.get(), nullptr);
1496
1497 ABinderRpc_Accessor* accessor2 =
1498 ABinderRpc_Accessor_fromBinder("wrong_service_name", binder.get());
1499 // The API checks for the expected service name that is associated with
1500 // the accessor!
1501 EXPECT_EQ(accessor2, nullptr);
1502
1503 accessor2 = ABinderRpc_Accessor_fromBinder("gshoe_service", binder.get());
1504 EXPECT_NE(accessor2, nullptr);
1505
1506 // this is a new ABinderRpc_Accessor object that wraps the underlying
1507 // libbinder object.
1508 EXPECT_NE(accessor, accessor2);
1509
1510 ndk::SpAIBinder binder2 = ndk::SpAIBinder(ABinderRpc_Accessor_asBinder(accessor2));
1511 EXPECT_EQ(binder.get(), binder2.get());
1512
1513 ABinderRpc_Accessor_delete(accessor2);
1514 }
1515
1516 EXPECT_FALSE(isDeleted);
1517 ABinderRpc_Accessor_delete(accessor);
1518 EXPECT_TRUE(isDeleted);
1519}
1520
1521TEST_F(BinderARpcNdk, ARpcRequireProviderOnDeleteCallback) {
1522 EXPECT_EQ(nullptr,
1523 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1524 kARpcNumSupportedServices,
1525 reinterpret_cast<void*>(1), nullptr));
1526}
1527
1528TEST_F(BinderARpcNdk, ARpcRequireInfoOnDeleteCallback) {
1529 EXPECT_EQ(nullptr,
1530 ABinderRpc_Accessor_new("the_best_service_name", infoProvider,
1531 reinterpret_cast<void*>(1), nullptr));
1532}
1533
1534TEST_F(BinderARpcNdk, ARpcNoDataNoProviderOnDeleteCallback) {
1535 ABinderRpc_AccessorProvider* provider =
1536 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1537 kARpcNumSupportedServices, nullptr, nullptr);
1538 ASSERT_NE(nullptr, provider);
1539 ABinderRpc_unregisterAccessorProvider(provider);
1540}
1541
1542TEST_F(BinderARpcNdk, ARpcNoDataNoInfoOnDeleteCallback) {
1543 ABinderRpc_Accessor* accessor =
1544 ABinderRpc_Accessor_new("the_best_service_name", infoProvider, nullptr, nullptr);
1545 ASSERT_NE(nullptr, accessor);
1546 ABinderRpc_Accessor_delete(accessor);
1547}
1548
Devin Moorec370db42024-08-09 23:18:05 +00001549TEST_F(BinderARpcNdk, ARpcNullArgs_ConnectionInfo_new) {
1550 sockaddr_storage addr;
1551 EXPECT_EQ(nullptr, ABinderRpc_ConnectionInfo_new(reinterpret_cast<const sockaddr*>(&addr), 0));
1552}
1553
Devin Moore0555fbf2024-08-29 15:51:50 +00001554TEST_F(BinderARpcNdk, ARpcDelegateAccessorWrongInstance) {
1555 AccessorProviderData* data = new AccessorProviderData();
1556 ABinderRpc_Accessor* accessor = getAccessor(kARpcInstance, data);
1557 ASSERT_NE(accessor, nullptr);
1558 AIBinder* localAccessorBinder = ABinderRpc_Accessor_asBinder(accessor);
1559 EXPECT_NE(localAccessorBinder, nullptr);
1560
1561 AIBinder* delegatorBinder = nullptr;
1562 binder_status_t status =
1563 ABinderRpc_Accessor_delegateAccessor("bar", localAccessorBinder, &delegatorBinder);
1564 EXPECT_EQ(status, NAME_NOT_FOUND);
1565
1566 AIBinder_decStrong(localAccessorBinder);
1567 ABinderRpc_Accessor_delete(accessor);
1568 delete data;
1569}
1570
1571TEST_F(BinderARpcNdk, ARpcDelegateNonAccessor) {
1572 auto service = defaultServiceManager()->checkService(String16(kKnownAidlService));
1573 ASSERT_NE(nullptr, service);
1574 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(service));
1575
1576 AIBinder* delegatorBinder = nullptr;
1577 binder_status_t status =
1578 ABinderRpc_Accessor_delegateAccessor("bar", binder.get(), &delegatorBinder);
1579
1580 EXPECT_EQ(status, BAD_TYPE);
1581}
1582
1583inline void getServiceTest(BinderRpcTestProcessSession& proc,
1584 ABinderRpc_AccessorProvider_getAccessorCallback getAccessor) {
Devin Moorec370db42024-08-09 23:18:05 +00001585 constexpr size_t kNumThreads = 10;
1586 bool isDeleted = false;
1587
Devin Moorec370db42024-08-09 23:18:05 +00001588 AccessorProviderData* data =
1589 new AccessorProviderData{proc.proc->sessions[0].addr, proc.proc->sessions[0].addrLen,
1590 &isDeleted};
Devin Moorec370db42024-08-09 23:18:05 +00001591 ABinderRpc_AccessorProvider* provider =
1592 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1593 kARpcNumSupportedServices, data,
1594 accessorProviderDataOnDelete);
Devin Moorec370db42024-08-09 23:18:05 +00001595 EXPECT_NE(provider, nullptr);
1596 EXPECT_FALSE(isDeleted);
1597
1598 {
1599 ndk::SpAIBinder binder = ndk::SpAIBinder(AServiceManager_checkService(kARpcInstance));
1600 ASSERT_NE(binder.get(), nullptr);
1601 EXPECT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1602 }
1603
1604 ABinderRpc_unregisterAccessorProvider(provider);
1605 EXPECT_TRUE(isDeleted);
1606
1607 waitForExtraSessionCleanup(proc);
1608}
1609
Devin Moore0555fbf2024-08-29 15:51:50 +00001610TEST_P(BinderRpcAccessor, ARpcGetService) {
1611 constexpr size_t kNumThreads = 10;
1612 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1613 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1614
1615 getServiceTest(proc, getAccessor);
1616}
1617
1618// Create accessors and wrap each of the accessors in a delegator
1619ABinderRpc_Accessor* getDelegatedAccessor(const char* instance, void* cookie) {
1620 ABinderRpc_Accessor* accessor = getAccessor(instance, cookie);
1621 AIBinder* accessorBinder = ABinderRpc_Accessor_asBinder(accessor);
1622 // Once we have a handle to the AIBinder which holds a reference to the
1623 // underlying accessor IBinder, we can get rid of the ABinderRpc_Accessor
1624 ABinderRpc_Accessor_delete(accessor);
1625
1626 AIBinder* delegatorBinder = nullptr;
1627 binder_status_t status =
1628 ABinderRpc_Accessor_delegateAccessor(instance, accessorBinder, &delegatorBinder);
1629 // No longer need this AIBinder. The delegator has a reference to the
1630 // underlying IBinder on success, and on failure we are done here.
1631 AIBinder_decStrong(accessorBinder);
1632 if (status != OK || delegatorBinder == nullptr) {
1633 ALOGE("Unexpected behavior. Status: %s, delegator ptr: %p", statusToString(status).c_str(),
1634 delegatorBinder);
1635 return nullptr;
1636 }
1637
1638 return ABinderRpc_Accessor_fromBinder(instance, delegatorBinder);
1639}
1640
1641TEST_P(BinderRpcAccessor, ARpcGetServiceWithDelegator) {
1642 constexpr size_t kNumThreads = 10;
1643 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1644 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1645
1646 getServiceTest(proc, getDelegatedAccessor);
1647}
1648
Devin Moore18f63752024-08-08 21:01:24 +00001649#endif // BINDER_WITH_KERNEL_IPC
1650
Andrei Homescud65666d2023-03-03 07:28:02 +00001651#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001652
1653static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1654 std::vector<BinderRpc::ParamType> ret;
1655
1656 for (const auto& clientVersion : testVersions()) {
1657 for (const auto& serverVersion : testVersions()) {
1658 ret.push_back(BinderRpc::ParamType{
1659 .type = SocketType::TIPC,
1660 .security = RpcSecurity::RAW,
1661 .clientVersion = clientVersion,
1662 .serverVersion = serverVersion,
1663 .singleThreaded = true,
1664 .noKernel = true,
1665 });
1666 }
1667 }
1668
1669 return ret;
1670}
1671
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001672INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1673 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001674#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001675bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001676 // We don't need to enable TLS to know if vsock is supported.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001677 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001678 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001679
1680 if (errno == EAFNOSUPPORT) {
1681 return false;
1682 }
1683
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001684 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001685
1686 sockaddr_vm serverAddr{
1687 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001688 .svm_port = VMADDR_PORT_ANY,
Andrei Homescu992a4052022-06-28 21:26:18 +00001689 .svm_cid = VMADDR_CID_ANY,
1690 };
1691 int ret = TEMP_FAILURE_RETRY(
1692 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001693 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
Andrei Homescu992a4052022-06-28 21:26:18 +00001694 strerror(errno));
1695
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001696 socklen_t len = sizeof(serverAddr);
1697 ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
1698 LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
Hannah.Hsu6b1036f2024-07-09 11:20:20 +08001699 LOG_ALWAYS_FATAL_IF(len < static_cast<socklen_t>(sizeof(serverAddr)),
1700 "getsockname didn't read the full addr struct");
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001701
Andrei Homescu992a4052022-06-28 21:26:18 +00001702 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001703 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001704 strerror(errno));
1705
1706 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1707 // to see if the kernel supports it. It's safe to use a blocking
1708 // connect because vsock sockets have a 2 second connection timeout,
1709 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001710 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001711 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001712 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
1713 serverAddr.svm_port, strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001714
1715 bool success = false;
1716 sockaddr_vm connectAddr{
1717 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001718 .svm_port = serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001719 .svm_cid = VMADDR_CID_LOCAL,
1720 };
1721 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1722 sizeof(connectAddr)));
1723 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001724 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001725 while (true) {
1726 pollfd pfd[]{
1727 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1728 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1729 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001730 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001731 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1732
1733 if (pfd[0].revents & POLLIN) {
1734 sockaddr_vm acceptAddr;
1735 socklen_t acceptAddrLen = sizeof(acceptAddr);
1736 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1737 reinterpret_cast<sockaddr*>(&acceptAddr),
1738 &acceptAddrLen, SOCK_CLOEXEC));
1739 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1740 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1741 "Truncated address");
1742
1743 // Store the fd in acceptFd so we keep the connection alive
1744 // while polling connectFd
1745 acceptFd.reset(ret);
1746 }
1747
1748 if (pfd[1].revents & POLLOUT) {
1749 // Connect either succeeded or timed out
1750 int connectErrno;
1751 socklen_t connectErrnoLen = sizeof(connectErrno);
1752 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1753 &connectErrnoLen);
1754 LOG_ALWAYS_FATAL_IF(ret == -1,
1755 "Could not getsockopt() after connect() "
1756 "on non-blocking socket: %s.",
1757 strerror(errno));
1758
1759 // We're done, this is all we wanted
1760 success = connectErrno == 0;
1761 break;
1762 }
1763 }
1764 } else {
1765 success = ret == 0;
1766 }
1767
1768 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1769
1770 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001771}
1772
Yifan Hong1deca4b2021-09-10 16:16:44 -07001773static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001774 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1775 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001776
1777 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001778
Steven Moreland9f250b02023-05-16 23:27:42 +00001779#ifdef __BIONIC__
1780 // Devices may not have vsock support. AVF tests will verify whether they do, but
1781 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001782 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001783#else
1784 // On host machines, we always assume we have vsock loopback. If we don't, the
1785 // subsequent failures will be more clear than showing one now.
1786 static bool hasVsockLoopback = true;
1787#endif
Steven Morelandda573042021-06-12 01:13:45 +00001788
1789 if (hasVsockLoopback) {
1790 ret.push_back(SocketType::VSOCK);
1791 }
1792
1793 return ret;
1794}
1795
Steven Morelandb469f432023-07-28 22:13:47 +00001796static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1797 std::vector<BinderRpc::ParamType> ret;
1798
Steven Morelandf7421432023-07-28 22:41:44 +00001799 constexpr bool full = false;
1800
Steven Morelandb469f432023-07-28 22:13:47 +00001801 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001802 if (full || type == SocketType::UNIX) {
1803 for (const auto& security : RpcSecurityValues()) {
1804 for (const auto& clientVersion : testVersions()) {
1805 for (const auto& serverVersion : testVersions()) {
1806 for (bool singleThreaded : {false, true}) {
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001807 for (bool noKernel : noKernelValues()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001808 ret.push_back(BinderRpc::ParamType{
1809 .type = type,
1810 .security = security,
1811 .clientVersion = clientVersion,
1812 .serverVersion = serverVersion,
1813 .singleThreaded = singleThreaded,
1814 .noKernel = noKernel,
1815 });
1816 }
Steven Morelandb469f432023-07-28 22:13:47 +00001817 }
1818 }
1819 }
1820 }
Steven Morelandf7421432023-07-28 22:41:44 +00001821 } else {
1822 ret.push_back(BinderRpc::ParamType{
1823 .type = type,
1824 .security = RpcSecurity::RAW,
1825 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1826 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1827 .singleThreaded = false,
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001828 .noKernel = !kEnableKernelIpcTesting,
Steven Morelandf7421432023-07-28 22:41:44 +00001829 });
Steven Morelandb469f432023-07-28 22:13:47 +00001830 }
1831 }
Steven Morelandf7421432023-07-28 22:41:44 +00001832
Steven Morelandb469f432023-07-28 22:13:47 +00001833 return ret;
1834}
1835
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001836INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1837 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001838
Devin Moore18f63752024-08-08 21:01:24 +00001839#ifdef BINDER_WITH_KERNEL_IPC
1840INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpcAccessor, ::testing::ValuesIn(getBinderRpcParams()),
1841 BinderRpc::PrintParamInfo);
1842#endif // BINDER_WITH_KERNEL_IPC
1843
Yifan Hong702115c2021-06-24 15:39:18 -07001844class BinderRpcServerRootObject
1845 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001846
1847TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1848 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1849 auto setRootObject = [](bool isStrong) -> SetFn {
1850 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1851 };
1852
Yifan Hong702115c2021-06-24 15:39:18 -07001853 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001854 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001855 auto binder1 = sp<BBinder>::make();
1856 IBinder* binderRaw1 = binder1.get();
1857 setRootObject(isStrong1)(server.get(), binder1);
1858 EXPECT_EQ(binderRaw1, server->getRootObject());
1859 binder1.clear();
1860 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1861
1862 auto binder2 = sp<BBinder>::make();
1863 IBinder* binderRaw2 = binder2.get();
1864 setRootObject(isStrong2)(server.get(), binder2);
1865 EXPECT_EQ(binderRaw2, server->getRootObject());
1866 binder2.clear();
1867 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1868}
1869
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001870INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1871 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1872 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001873
Yifan Hong1a235852021-05-13 16:07:47 -07001874class OneOffSignal {
1875public:
1876 // If notify() was previously called, or is called within |duration|, return true; else false.
1877 template <typename R, typename P>
1878 bool wait(std::chrono::duration<R, P> duration) {
1879 std::unique_lock<std::mutex> lock(mMutex);
1880 return mCv.wait_for(lock, duration, [this] { return mValue; });
1881 }
1882 void notify() {
1883 std::unique_lock<std::mutex> lock(mMutex);
1884 mValue = true;
1885 lock.unlock();
1886 mCv.notify_all();
1887 }
1888
1889private:
1890 std::mutex mMutex;
1891 std::condition_variable mCv;
1892 bool mValue = false;
1893};
1894
Yifan Hong194acf22021-06-29 18:44:56 -07001895TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001896 bool expectDebuggable = false;
1897#if defined(__ANDROID__)
1898 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1899 android::base::GetProperty("ro.build.type", "") != "user";
1900#else
Yifan Hong194acf22021-06-29 18:44:56 -07001901 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1902 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1903 "to binderHostDeviceTest. Hence, just disable this test on host.";
1904#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001905 if constexpr (!kEnableKernelIpc) {
1906 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1907 "at build time.";
1908 }
1909
Yifan Hong194acf22021-06-29 18:44:56 -07001910 sp<IServiceManager> sm = defaultServiceManager();
1911 ASSERT_NE(nullptr, sm);
1912 // Any Java service with non-empty getInterfaceDescriptor() would do.
Devin Moore29db8602024-08-14 22:21:04 +00001913 // Let's pick activity.
Devin Moore0555fbf2024-08-29 15:51:50 +00001914 auto binder = sm->checkService(String16(kKnownAidlService));
Yifan Hong194acf22021-06-29 18:44:56 -07001915 ASSERT_NE(nullptr, binder);
1916 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001917 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001918 ASSERT_EQ(OK, binder->pingBinder());
1919
1920 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001921 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001922 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001923 auto socket = rpcServer->releaseServer();
1924
1925 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001926 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1927
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001928 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001929 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001930 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1931 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001932 << statusToString(setRpcClientDebugStatus);
1933 GTEST_SKIP();
1934 }
1935
1936 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001937
1938 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001939 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001940 auto rpcBinder = rpcSession->getRootObject();
1941 ASSERT_NE(nullptr, rpcBinder);
1942
1943 ASSERT_EQ(OK, rpcBinder->pingBinder());
1944
1945 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1946 << "getInterfaceDescriptor should not crash system_server";
1947 ASSERT_EQ(OK, rpcBinder->pingBinder());
1948}
1949
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001950class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1951public:
1952 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001953 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001954 std::to_string(std::get<1>(info.param));
1955 }
1956};
1957
1958TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001959 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001960 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001961 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001962 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001963 ASSERT_FALSE(server->hasServer());
1964 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1965 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001966 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001967 ASSERT_FALSE(server->hasServer());
1968 ASSERT_EQ(sinkFd, retrieved.get());
1969}
1970
1971TEST_P(BinderRpcServerOnly, Shutdown) {
1972 if constexpr (!kEnableRpcThreads) {
1973 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1974 }
1975
1976 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001977 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001978 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001979 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1980 auto joinEnds = std::make_shared<OneOffSignal>();
1981
1982 // If things are broken and the thread never stops, don't block other tests. Because the thread
1983 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1984 // shared pointers are passed.
1985 std::thread([server, joinEnds] {
1986 server->join();
1987 joinEnds->notify();
1988 }).detach();
1989
1990 bool shutdown = false;
1991 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001992 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001993 if (server->shutdown()) shutdown = true;
1994 }
1995 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1996
1997 ASSERT_TRUE(joinEnds->wait(2s))
1998 << "After server->shutdown() returns true, join() did not stop after 2s";
1999}
2000
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002001INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
2002 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
2003 ::testing::ValuesIn(testVersions())),
2004 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07002005
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002006class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002007public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00002008 // Only parameterized only server version because `RpcSession` is bypassed
2009 // in the client half of the tests.
2010 using Param =
2011 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002012 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002013
2014 // A server that handles client socket connections.
2015 class Server {
2016 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002017 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01002018
Yifan Hong1deca4b2021-09-10 16:16:44 -07002019 explicit Server() {}
2020 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07002021 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002022 [[nodiscard]] AssertionResult setUp(
2023 const Param& param,
2024 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002025 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00002026 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00002027 if (!rpcServer->setProtocolVersion(serverVersion)) {
2028 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
2029 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002030 switch (socketType) {
2031 case SocketType::PRECONNECTED: {
2032 return AssertionFailure() << "Not supported by this test";
2033 } break;
2034 case SocketType::UNIX: {
2035 auto addr = allocateSocketAddress();
2036 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
2037 if (status != OK) {
2038 return AssertionFailure()
2039 << "setupUnixDomainServer: " << statusToString(status);
2040 }
2041 mConnectToServer = [addr] {
2042 return connectTo(UnixSocketAddress(addr.c_str()));
2043 };
2044 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01002045 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002046 unique_fd bootstrapFdClient, bootstrapFdServer;
2047 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01002048 return AssertionFailure() << "Socketpair() failed";
2049 }
2050 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
2051 std::move(bootstrapFdServer));
2052 if (status != OK) {
2053 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
2054 << statusToString(status);
2055 }
2056 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
2057 mAcceptConnection = &Server::recvmsgServerConnection;
2058 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
2059 } break;
Alice Wang893a9912022-10-24 10:44:09 +00002060 case SocketType::UNIX_RAW: {
2061 auto addr = allocateSocketAddress();
2062 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
2063 if (status != OK) {
2064 return AssertionFailure()
2065 << "setupRawSocketServer: " << statusToString(status);
2066 }
2067 mConnectToServer = [addr] {
2068 return connectTo(UnixSocketAddress(addr.c_str()));
2069 };
2070 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002071 case SocketType::VSOCK: {
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07002072 unsigned port;
2073 auto status =
2074 rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002075 if (status != OK) {
2076 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
2077 }
2078 mConnectToServer = [port] {
2079 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
2080 };
2081 } break;
2082 case SocketType::INET: {
2083 unsigned int port;
2084 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
2085 if (status != OK) {
2086 return AssertionFailure() << "setupInetServer: " << statusToString(status);
2087 }
2088 mConnectToServer = [port] {
2089 const char* addr = kLocalInetAddress;
2090 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002091 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07002092 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
2093 auto fd = connectTo(
2094 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
2095 if (fd.ok()) return fd;
2096 }
2097 ALOGE("None of the socket address resolved for %s:%u can be connected",
2098 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002099 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07002100 };
Andrei Homescu68a55612022-08-02 01:25:15 +00002101 } break;
2102 case SocketType::TIPC: {
2103 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
2104 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002105 }
2106 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00002107 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00002108 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07002109 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
2110 mSetup = true;
2111 return AssertionSuccess();
2112 }
2113 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2114 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2115 return mCertVerifier;
2116 }
2117 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
2118 void start() {
2119 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
2120 mThread = std::make_unique<std::thread>(&Server::run, this);
2121 }
David Brazdil21c887c2022-09-23 12:25:18 +01002122
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002123 unique_fd acceptServerConnection() {
2124 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01002125 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
2126 }
2127
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002128 unique_fd recvmsgServerConnection() {
2129 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01002130 int buf;
2131 iovec iov{&buf, sizeof(buf)};
2132
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00002133 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002134 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01002135 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002136 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
2137 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002138 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01002139 }
2140
Yifan Hong1deca4b2021-09-10 16:16:44 -07002141 void run() {
2142 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
2143
2144 std::vector<std::thread> threads;
2145 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002146 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002147 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
2148 }
2149
2150 for (auto& thread : threads) thread.join();
2151 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002152 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002153 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00002154 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00002155 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002156 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07002157 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002158 }
Yifan Honge07d2732021-09-13 21:59:14 -07002159 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07002160 shutdown();
2161 join();
2162 }
2163 void shutdown() { mFdTrigger->trigger(); }
2164
2165 void setPostConnect(
2166 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
2167 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002168 }
2169
2170 private:
2171 std::unique_ptr<std::thread> mThread;
2172 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01002173 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002174 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01002175 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002176 std::unique_ptr<RpcTransportCtx> mCtx;
2177 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2178 std::make_shared<RpcCertificateVerifierSimple>();
2179 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07002180 // The function invoked after connection and handshake. By default, it is
2181 // |defaultPostConnect| that sends |kMessage| to the client.
2182 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
2183 Server::defaultPostConnect;
2184
2185 void join() {
2186 if (mThread != nullptr) {
2187 mThread->join();
2188 mThread = nullptr;
2189 }
2190 }
2191
2192 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
2193 FdTrigger* fdTrigger) {
2194 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002195 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002196 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00002197 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002198 if (status != OK) return AssertionFailure() << statusToString(status);
2199 return AssertionSuccess();
2200 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002201 };
2202
2203 class Client {
2204 public:
2205 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
2206 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002207 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002208 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
2209 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002210 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00002211 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07002212 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
2213 return AssertionSuccess();
2214 }
2215 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2216 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2217 return mCertVerifier;
2218 }
Yifan Hong67519322021-09-13 18:51:16 -07002219 // connect() and do handshake
2220 bool setUpTransport() {
2221 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00002222 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07002223 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
2224 return mClientTransport != nullptr;
2225 }
2226 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
2227 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
2228 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002229 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002230 status_t readStatus =
2231 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00002232 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002233 if (readStatus != OK) {
2234 return AssertionFailure() << statusToString(readStatus);
2235 }
2236 if (readMessage != expectedMessage) {
2237 return AssertionFailure()
2238 << "Expected " << expectedMessage << ", actual " << readMessage;
2239 }
2240 return AssertionSuccess();
2241 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002242 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07002243 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002244 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
2245 return;
2246 }
2247 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07002248 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002249 }
2250
Pawan49d74cb2022-08-03 21:19:11 +00002251 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
2252
Yifan Hong1deca4b2021-09-10 16:16:44 -07002253 private:
2254 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00002255 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002256 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
2257 std::unique_ptr<RpcTransportCtx> mCtx;
2258 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2259 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07002260 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002261 };
2262
2263 // Make A trust B.
2264 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002265 static status_t trust(RpcSecurity rpcSecurity,
2266 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
2267 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002268 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07002269 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
2270 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
2271 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002272 }
2273
2274 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002275};
2276
2277class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
2278public:
2279 using Server = RpcTransportTestUtils::Server;
2280 using Client = RpcTransportTestUtils::Client;
2281 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002282 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00002283 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002284 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00002285 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002286 return ret;
2287 }
2288 static std::vector<ParamType> getRpcTranportTestParams() {
2289 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002290 for (auto serverVersion : testVersions()) {
2291 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2292 for (auto rpcSecurity : RpcSecurityValues()) {
2293 switch (rpcSecurity) {
2294 case RpcSecurity::RAW: {
2295 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2296 } break;
2297 case RpcSecurity::TLS: {
2298 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2299 serverVersion);
2300 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2301 serverVersion);
2302 } break;
2303 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002304 }
2305 }
2306 }
2307 return ret;
2308 }
2309 template <typename A, typename B>
2310 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002311 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2312 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002313 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2314 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002315 void SetUp() override {
2316 if constexpr (!kEnableRpcThreads) {
2317 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2318 }
2319 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002320};
2321
2322TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002323 auto server = std::make_unique<Server>();
2324 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002325
2326 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002327 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002328
2329 ASSERT_EQ(OK, trust(&client, server));
2330 ASSERT_EQ(OK, trust(server, &client));
2331
2332 server->start();
2333 client.run();
2334}
2335
2336TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002337 auto server = std::make_unique<Server>();
2338 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002339
2340 std::vector<Client> clients;
2341 for (int i = 0; i < 2; i++) {
2342 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002343 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002344 ASSERT_EQ(OK, trust(&client, server));
2345 ASSERT_EQ(OK, trust(server, &client));
2346 }
2347
2348 server->start();
2349 for (auto& client : clients) client.run();
2350}
2351
2352TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002353 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2354 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002355
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002356 auto untrustedServer = std::make_unique<Server>();
2357 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002358
2359 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002360 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002361
2362 ASSERT_EQ(OK, trust(untrustedServer, &client));
2363
2364 untrustedServer->start();
2365
2366 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2367 // the client can't verify the server's identity.
2368 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2369 client.run(handshakeOk);
2370}
2371TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002372 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2373 (void)serverVersion;
2374
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002375 auto validServer = std::make_unique<Server>();
2376 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002377
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002378 auto maliciousServer = std::make_unique<Server>();
2379 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002380
2381 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002382 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002383
2384 ASSERT_EQ(OK, trust(&client, validServer));
2385 ASSERT_EQ(OK, trust(validServer, &client));
2386 ASSERT_EQ(OK, trust(maliciousServer, &client));
2387
2388 maliciousServer->start();
2389
2390 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2391 // the client can't verify the server's identity.
2392 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2393 client.run(handshakeOk);
2394}
2395
2396TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002397 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2398 (void)serverVersion;
2399
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002400 auto server = std::make_unique<Server>();
2401 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002402
2403 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002404 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002405
2406 ASSERT_EQ(OK, trust(&client, server));
2407
2408 server->start();
2409
2410 // For TLS, Client should be able to verify server's identity, so client should see
2411 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2412 // identity and should drop the connection, so client shouldn't be able to read anything.
2413 bool readOk = rpcSecurity != RpcSecurity::TLS;
2414 client.run(true, readOk);
2415}
2416
2417TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002418 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2419 (void)serverVersion;
2420
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002421 auto server = std::make_unique<Server>();
2422 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002423
2424 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002425 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002426 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002427 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002428
2429 ASSERT_EQ(OK, trust(&validClient, server));
2430 ASSERT_EQ(OK, trust(&maliciousClient, server));
2431
2432 server->start();
2433
2434 // See UntrustedClient.
2435 bool readOk = rpcSecurity != RpcSecurity::TLS;
2436 maliciousClient.run(true, readOk);
2437}
2438
Yifan Hong67519322021-09-13 18:51:16 -07002439TEST_P(RpcTransportTest, Trigger) {
2440 std::string msg2 = ", world!";
2441 std::mutex writeMutex;
2442 std::condition_variable writeCv;
2443 bool shouldContinueWriting = false;
2444 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002445 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002446 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002447 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2448 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002449 if (status != OK) return AssertionFailure() << statusToString(status);
2450
2451 {
2452 std::unique_lock<std::mutex> lock(writeMutex);
2453 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2454 return AssertionFailure() << "write barrier not cleared in time!";
2455 }
2456 }
2457
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002458 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002459 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2460 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002461 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002462 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002463 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002464 << statusToString(status);
2465 return AssertionSuccess();
2466 };
2467
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002468 auto server = std::make_unique<Server>();
2469 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002470
2471 // Set up client
2472 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002473 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002474
2475 // Exchange keys
2476 ASSERT_EQ(OK, trust(&client, server));
2477 ASSERT_EQ(OK, trust(server, &client));
2478
2479 server->setPostConnect(serverPostConnect);
2480
Yifan Hong67519322021-09-13 18:51:16 -07002481 server->start();
2482 // connect() to server and do handshake
2483 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002484 // read the first message. This ensures that server has finished handshake and start handling
2485 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002486 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002487 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2488 // write is on an FdTrigger that has been shut down.
2489 server->shutdown();
2490 // Continues server thread to write the second message.
2491 {
Yifan Hong22211f82021-09-14 12:32:25 -07002492 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002493 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002494 }
Yifan Hong22211f82021-09-14 12:32:25 -07002495 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002496 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002497 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002498 // On the client side, second read fails with DEAD_OBJECT
2499 ASSERT_FALSE(client.readMessage(msg2));
2500}
2501
Pawan49d74cb2022-08-03 21:19:11 +00002502TEST_P(RpcTransportTest, CheckWaitingForRead) {
2503 std::mutex readMutex;
2504 std::condition_variable readCv;
2505 bool shouldContinueReading = false;
2506 // Server will write data on transport once its started
2507 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2508 std::string message(RpcTransportTestUtils::kMessage);
2509 iovec messageIov{message.data(), message.size()};
2510 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2511 std::nullopt, nullptr);
2512 if (status != OK) return AssertionFailure() << statusToString(status);
2513
2514 {
2515 std::unique_lock<std::mutex> lock(readMutex);
2516 shouldContinueReading = true;
2517 lock.unlock();
2518 readCv.notify_all();
2519 }
2520 return AssertionSuccess();
2521 };
2522
2523 // Setup Server and client
2524 auto server = std::make_unique<Server>();
2525 ASSERT_TRUE(server->setUp(GetParam()));
2526
2527 Client client(server->getConnectToServerFn());
2528 ASSERT_TRUE(client.setUp(GetParam()));
2529
2530 ASSERT_EQ(OK, trust(&client, server));
2531 ASSERT_EQ(OK, trust(server, &client));
2532 server->setPostConnect(serverPostConnect);
2533
2534 server->start();
2535 ASSERT_TRUE(client.setUpTransport());
2536 {
2537 // Wait till server writes data
2538 std::unique_lock<std::mutex> lock(readMutex);
2539 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2540 }
2541
2542 // Since there is no read polling here, we will get polling count 0
2543 ASSERT_FALSE(client.isTransportWaiting());
2544 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2545 // Thread should increment polling count, read and decrement polling count
2546 // Again, polling count should be zero here
2547 ASSERT_FALSE(client.isTransportWaiting());
2548
2549 server->shutdown();
2550}
2551
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002552INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2553 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2554 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002555
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002556class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002557 : public testing::TestWithParam<
2558 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002559public:
2560 template <typename A, typename B>
2561 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002562 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2563 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002564 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2565 }
2566 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002567 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2568 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2569 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002570 };
2571};
2572
2573TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002574 if constexpr (!kEnableRpcThreads) {
2575 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2576 }
2577
Frederick Mayledc07cf82022-05-26 20:30:12 +00002578 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002579
2580 std::vector<uint8_t> pkeyData, certData;
2581 {
2582 auto pkey = makeKeyPairForSelfSignedCert();
2583 ASSERT_NE(nullptr, pkey);
2584 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2585 ASSERT_NE(nullptr, cert);
2586 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2587 certData = serializeCertificate(cert.get(), certificateFormat);
2588 }
2589
2590 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2591 auto desCert = deserializeCertificate(certData, certificateFormat);
2592 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002593 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2594 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002595
2596 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2597 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2598
2599 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2600 ASSERT_TRUE(client.setUp(utilsParam));
2601
2602 ASSERT_EQ(OK, trust(&client, server));
2603 ASSERT_EQ(OK, trust(server, &client));
2604
2605 server->start();
2606 client.run();
2607}
2608
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002609INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002610 BinderRpc, RpcTransportTlsKeyTest,
2611 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2612 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002613 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2614 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002615 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002616#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002617
Steven Morelandc1635952021-04-01 16:20:47 +00002618} // namespace android
2619
2620int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002621 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002622 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002623
Steven Moreland5553ac42020-11-11 02:14:45 +00002624 return RUN_ALL_TESTS();
2625}