blob: 194553f872af7085557c52341fd84604fd006361 [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
Yifan Hong1deca4b2021-09-10 16:16:44 -070017#include <BinderRpcTestClientInfo.h>
18#include <BinderRpcTestServerInfo.h>
Steven Moreland659416d2021-05-11 00:47:50 +000019#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000020#include <BnBinderRpcSession.h>
21#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000022#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070023#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <android-base/logging.h>
Yifan Hongfe4b83f2021-11-08 16:29:53 -080025#include <android-base/properties.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000026#include <android-base/stringprintf.h>
Steven Moreland37aff182021-03-26 02:04:16 +000027#include <android/binder_auto_utils.h>
28#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000029#include <binder/Binder.h>
30#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000031#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <binder/IServiceManager.h>
33#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/RpcSession.h>
Yifan Honge0e53282021-09-23 18:37:21 -070036#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070037#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070038#include <binder/RpcTransport.h>
39#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070040#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000041#include <gtest/gtest.h>
42
Steven Morelandc1635952021-04-01 16:20:47 +000043#include <chrono>
44#include <cstdlib>
45#include <iostream>
46#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000047#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000048
Yifan Hong1deca4b2021-09-10 16:16:44 -070049#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000050#include <sys/prctl.h>
51#include <unistd.h>
52
Yifan Hong1deca4b2021-09-10 16:16:44 -070053#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070054#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070055#include "../RpcState.h" // for debugging
56#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000057
Yifan Hong1a235852021-05-13 16:07:47 -070058using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070059using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070060using testing::AssertionFailure;
61using testing::AssertionResult;
62using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070063
Steven Moreland5553ac42020-11-11 02:14:45 +000064namespace android {
65
Steven Morelandbf57bce2021-07-26 15:26:12 -070066static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
67 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000068const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070069
Yifan Hong92409752021-07-30 21:25:32 -070070enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070071
72static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070073 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070074}
75
Yifan Hong13c90062021-09-09 14:59:53 -070076static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070077 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
78 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070079 switch (rpcSecurity) {
80 case RpcSecurity::RAW:
81 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070082 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070083 if (verifier == nullptr) {
84 verifier = std::make_shared<RpcCertificateVerifierSimple>();
85 }
Yifan Hongffdaf952021-09-17 18:08:38 -070086 if (auth == nullptr) {
87 auth = std::make_unique<RpcAuthSelfSigned>();
88 }
89 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -070090 }
Yifan Hong702115c2021-06-24 15:39:18 -070091 default:
92 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
93 }
94}
95
Steven Moreland1fda67b2021-04-02 18:35:50 +000096TEST(BinderRpcParcel, EntireParcelFormatted) {
97 Parcel p;
98 p.writeInt32(3);
99
100 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
101}
102
Frederick Mayledc07cf82022-05-26 20:30:12 +0000103class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -0700104public:
105 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000106 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
107 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -0700108 }
109};
110
Frederick Mayledc07cf82022-05-26 20:30:12 +0000111TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700112 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
113 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +0000114 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
115 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700116 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700117 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700118 ASSERT_TRUE(server->hasServer());
119 base::unique_fd retrieved = server->releaseServer();
120 ASSERT_FALSE(server->hasServer());
121 ASSERT_EQ(sinkFd, retrieved.get());
122}
123
Steven Morelandbf57bce2021-07-26 15:26:12 -0700124TEST(BinderRpc, CannotUseNextWireVersion) {
125 auto session = RpcSession::make();
126 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
127 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
128 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
129 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
130}
131
132TEST(BinderRpc, CanUseExperimentalWireVersion) {
133 auto session = RpcSession::make();
134 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
135}
136
Steven Moreland5553ac42020-11-11 02:14:45 +0000137using android::binder::Status;
138
139#define EXPECT_OK(status) \
140 do { \
141 Status stat = (status); \
142 EXPECT_TRUE(stat.isOk()) << stat; \
143 } while (false)
144
145class MyBinderRpcSession : public BnBinderRpcSession {
146public:
147 static std::atomic<int32_t> gNum;
148
149 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
150 Status getName(std::string* name) override {
151 *name = mName;
152 return Status::ok();
153 }
154 ~MyBinderRpcSession() { gNum--; }
155
156private:
157 std::string mName;
158};
159std::atomic<int32_t> MyBinderRpcSession::gNum;
160
Steven Moreland659416d2021-05-11 00:47:50 +0000161class MyBinderRpcCallback : public BnBinderRpcCallback {
162 Status sendCallback(const std::string& value) {
163 std::unique_lock _l(mMutex);
164 mValues.push_back(value);
165 _l.unlock();
166 mCv.notify_one();
167 return Status::ok();
168 }
169 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
170
171public:
172 std::mutex mMutex;
173 std::condition_variable mCv;
174 std::vector<std::string> mValues;
175};
176
Steven Moreland5553ac42020-11-11 02:14:45 +0000177class MyBinderRpcTest : public BnBinderRpcTest {
178public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000179 wp<RpcServer> server;
Steven Moreland51c44a92021-10-14 16:50:35 -0700180 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181
182 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000183 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000184 return Status::ok();
185 }
186 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000187 *strstr = str + str;
188 return Status::ok();
189 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700190 Status getClientPort(int* out) override {
191 *out = port;
192 return Status::ok();
193 }
Steven Moreland736664b2021-05-01 04:27:25 +0000194 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000195 sp<RpcServer> spServer = server.promote();
196 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
198 }
Steven Moreland736664b2021-05-01 04:27:25 +0000199 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000200 for (auto session : spServer->listSessions()) {
201 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000202 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000203 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000204 return Status::ok();
205 }
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000206 Status getNullBinder(sp<IBinder>* out) override {
207 out->clear();
208 return Status::ok();
209 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000210 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
211 if (binder == nullptr) {
212 std::cout << "Received null binder!" << std::endl;
213 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
214 }
215 *out = binder->pingBinder();
216 return Status::ok();
217 }
218 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
219 *out = binder;
220 return Status::ok();
221 }
222 static sp<IBinder> mHeldBinder;
223 Status holdBinder(const sp<IBinder>& binder) override {
224 mHeldBinder = binder;
225 return Status::ok();
226 }
227 Status getHeldBinder(sp<IBinder>* held) override {
228 *held = mHeldBinder;
229 return Status::ok();
230 }
231 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
232 if (count <= 0) return Status::ok();
233 return binder->nestMe(this, count - 1);
234 }
235 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
236 static sp<IBinder> binder = new BBinder;
237 *out = binder;
238 return Status::ok();
239 }
240 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
241 *out = new MyBinderRpcSession(name);
242 return Status::ok();
243 }
244 Status getNumOpenSessions(int32_t* out) override {
245 *out = MyBinderRpcSession::gNum;
246 return Status::ok();
247 }
248
249 std::mutex blockMutex;
250 Status lock() override {
251 blockMutex.lock();
252 return Status::ok();
253 }
254 Status unlockInMsAsync(int32_t ms) override {
255 usleep(ms * 1000);
256 blockMutex.unlock();
257 return Status::ok();
258 }
259 Status lockUnlock() override {
260 std::lock_guard<std::mutex> _l(blockMutex);
261 return Status::ok();
262 }
263
264 Status sleepMs(int32_t ms) override {
265 usleep(ms * 1000);
266 return Status::ok();
267 }
268
269 Status sleepMsAsync(int32_t ms) override {
270 // In-process binder calls are asynchronous, but the call to this method
271 // is synchronous wrt its client. This in/out-process threading model
272 // diffentiation is a classic binder leaky abstraction (for better or
273 // worse) and is preserved here the way binder sockets plugs itself
274 // into BpBinder, as nothing is changed at the higher levels
275 // (IInterface) which result in this behavior.
276 return sleepMs(ms);
277 }
278
Steven Moreland659416d2021-05-11 00:47:50 +0000279 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
280 const std::string& value) override {
281 if (callback == nullptr) {
282 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
283 }
284
285 if (delayed) {
286 std::thread([=]() {
287 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000288 Status status = doCallback(callback, oneway, false, value);
289 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000290 }).detach();
291 return Status::ok();
292 }
293
294 if (oneway) {
295 return callback->sendOnewayCallback(value);
296 }
297
298 return callback->sendCallback(value);
299 }
300
Steven Morelandc7d40132021-06-10 03:42:11 +0000301 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
302 const std::string& value) override {
303 return doCallback(callback, oneway, delayed, value);
304 }
305
Steven Moreland5553ac42020-11-11 02:14:45 +0000306 Status die(bool cleanup) override {
307 if (cleanup) {
308 exit(1);
309 } else {
310 _exit(1);
311 }
312 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000313
314 Status scheduleShutdown() override {
315 sp<RpcServer> strongServer = server.promote();
316 if (strongServer == nullptr) {
317 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
318 }
319 std::thread([=] {
320 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
321 }).detach();
322 return Status::ok();
323 }
324
Steven Morelandd7302072021-05-15 01:32:04 +0000325 Status useKernelBinderCallingId() override {
326 // this is WRONG! It does not make sense when using RPC binder, and
327 // because it is SO wrong, and so much code calls this, it should abort!
328
329 (void)IPCThreadState::self()->getCallingPid();
330 return Status::ok();
331 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000332};
333sp<IBinder> MyBinderRpcTest::mHeldBinder;
334
Frederick Maylea12b0962022-06-25 01:13:22 +0000335static std::string WaitStatusToString(int wstatus) {
336 if (WIFEXITED(wstatus)) {
337 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
338 }
339 if (WIFSIGNALED(wstatus)) {
340 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
341 }
342 return base::StringPrintf("unexpected state %d", wstatus);
343}
344
Steven Moreland5553ac42020-11-11 02:14:45 +0000345class Process {
346public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700347 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700348 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
349 android::base::borrowed_fd /* readEnd */)>& f) {
350 android::base::unique_fd childWriteEnd;
351 android::base::unique_fd childReadEnd;
352 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
353 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000354 if (0 == (mPid = fork())) {
355 // racey: assume parent doesn't crash before this is set
356 prctl(PR_SET_PDEATHSIG, SIGHUP);
357
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000359
360 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000361 }
362 }
363 ~Process() {
364 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000365 int wstatus;
366 waitpid(mPid, &wstatus, 0);
367 if (mCustomExitStatusCheck) {
368 mCustomExitStatusCheck(wstatus);
369 } else {
370 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
371 << "server process failed: " << WaitStatusToString(wstatus);
372 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000373 }
374 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700375 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700376 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000377
Frederick Maylea12b0962022-06-25 01:13:22 +0000378 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
379 mCustomExitStatusCheck = std::move(f);
380 }
381
Steven Moreland5553ac42020-11-11 02:14:45 +0000382private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000383 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000384 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700385 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700386 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000387};
388
389static std::string allocateSocketAddress() {
390 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000391 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700392 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
393 unlink(ret.c_str());
394 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000395};
396
Steven Morelandda573042021-06-12 01:13:45 +0000397static unsigned int allocateVsockPort() {
398 static unsigned int vsockPort = 3456;
399 return vsockPort++;
400}
401
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 // reference to process hosting a socket server
404 Process host;
405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406 struct SessionInfo {
407 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000408 sp<IBinder> root;
409 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000410
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411 // client session objects associated with other process
412 // each one represents a separate session
413 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000414
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 ProcessSession(ProcessSession&&) = default;
416 ~ProcessSession() {
417 for (auto& session : sessions) {
418 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000419 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000420
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421 for (auto& info : sessions) {
422 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000423
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000424 EXPECT_NE(nullptr, session);
425 EXPECT_NE(nullptr, session->state());
426 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000427
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000428 wp<RpcSession> weakSession = session;
429 session = nullptr;
430 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000431 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000432 }
433};
434
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000435// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000436// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437struct BinderRpcTestProcessSession {
438 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000439
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 sp<IBinder> rootBinder;
442
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000443 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000444 sp<IBinderRpcTest> rootIface;
445
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000447 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000448
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000449 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
450 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000451 EXPECT_NE(nullptr, rootIface);
452 if (rootIface == nullptr) return;
453
Steven Morelandaf4ca712021-05-24 23:22:08 +0000454 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000455 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000456 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000457 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000458 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000459 for (auto remoteCount : remoteCounts) {
460 EXPECT_EQ(remoteCount, 1);
461 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000462
Steven Moreland798e0d12021-07-14 23:19:25 +0000463 // even though it is on another thread, shutdown races with
464 // the transaction reply being written
465 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
466 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
467 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000468 }
469
470 rootIface = nullptr;
471 rootBinder = nullptr;
472 }
473};
474
Steven Morelandc1635952021-04-01 16:20:47 +0000475enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700476 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000477 UNIX,
478 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700479 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000480};
Yifan Hong702115c2021-06-24 15:39:18 -0700481static inline std::string PrintToString(SocketType socketType) {
482 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700483 case SocketType::PRECONNECTED:
484 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000485 case SocketType::UNIX:
486 return "unix_domain_socket";
487 case SocketType::VSOCK:
488 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700489 case SocketType::INET:
490 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000491 default:
492 LOG_ALWAYS_FATAL("Unknown socket type");
493 return "";
494 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000495}
Steven Morelandda573042021-06-12 01:13:45 +0000496
Yifan Hong1deca4b2021-09-10 16:16:44 -0700497static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700498 base::unique_fd serverFd(
499 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
500 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700501 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
502 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700503
504 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
505 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700506 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
507 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700508 }
509 return serverFd;
510}
511
Frederick Mayledc07cf82022-05-26 20:30:12 +0000512class BinderRpc
513 : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000514public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000515 struct Options {
516 size_t numThreads = 1;
517 size_t numSessions = 1;
518 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700519 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000520 };
521
Yifan Hong702115c2021-06-24 15:39:18 -0700522 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000523 auto [type, security, clientVersion, serverVersion] = info.param;
524 return PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
525 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Yifan Hong702115c2021-06-24 15:39:18 -0700526 }
527
Yifan Hong1deca4b2021-09-10 16:16:44 -0700528 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
529 uint64_t length = str.length();
530 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
531 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
532 }
533
534 static inline std::string readString(android::base::borrowed_fd fd) {
535 uint64_t length;
536 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
537 std::string ret(length, '\0');
538 CHECK(android::base::ReadFully(fd, ret.data(), length));
539 return ret;
540 }
541
542 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
543 Parcel parcel;
544 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
545 writeString(fd,
546 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
547 }
548
549 template <typename T>
550 static inline T readFromFd(android::base::borrowed_fd fd) {
551 std::string data = readString(fd);
552 Parcel parcel;
553 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
554 T object;
555 CHECK_EQ(OK, object.readFromParcel(&parcel));
556 return object;
557 }
558
Steven Morelandc1635952021-04-01 16:20:47 +0000559 // This creates a new process serving an interface on a certain number of
560 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000561 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000562 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
563 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000564
Yifan Hong702115c2021-06-24 15:39:18 -0700565 SocketType socketType = std::get<0>(GetParam());
566 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000567 uint32_t clientVersion = std::get<2>(GetParam());
568 uint32_t serverVersion = std::get<3>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000569
Steven Morelandda573042021-06-12 01:13:45 +0000570 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000571 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000572
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000573 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000574 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700575 android::base::borrowed_fd readEnd) {
576 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
577 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000578
Frederick Mayledc07cf82022-05-26 20:30:12 +0000579 server->setProtocolVersion(serverVersion);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000580 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000581
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000582 unsigned int outPort = 0;
583
Steven Morelandc1635952021-04-01 16:20:47 +0000584 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700585 case SocketType::PRECONNECTED:
586 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000587 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700588 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000589 break;
590 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700591 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000592 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700593 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700594 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700595 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700596 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700597 }
Steven Morelandc1635952021-04-01 16:20:47 +0000598 default:
599 LOG_ALWAYS_FATAL("Unknown socket type");
600 }
601
Yifan Hong1deca4b2021-09-10 16:16:44 -0700602 BinderRpcTestServerInfo serverInfo;
603 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700604 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700605 writeToFd(writeEnd, serverInfo);
606 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
607
608 if (rpcSecurity == RpcSecurity::TLS) {
609 for (const auto& clientCert : clientInfo.certs) {
610 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700611 certVerifier
612 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
613 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700614 }
615 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000616
Steven Moreland611d15f2021-05-01 01:28:27 +0000617 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000618
Steven Morelandf137de92021-04-24 01:54:26 +0000619 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000620
621 // Another thread calls shutdown. Wait for it to complete.
622 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000623 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000624 };
625
Yifan Hong1deca4b2021-09-10 16:16:44 -0700626 std::vector<sp<RpcSession>> sessions;
627 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
628 for (size_t i = 0; i < options.numSessions; i++) {
629 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
630 }
631
632 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
633 BinderRpcTestClientInfo clientInfo;
634 for (const auto& session : sessions) {
635 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700636 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700637 }
638 writeToFd(ret.host.writeEnd(), clientInfo);
639
640 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700641 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700642 CHECK_NE(0, serverInfo.port);
643 }
644
645 if (rpcSecurity == RpcSecurity::TLS) {
646 const auto& serverCert = serverInfo.cert.data;
647 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700648 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
649 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700650 }
651
Steven Moreland2372f9d2021-08-05 15:42:01 -0700652 status_t status;
653
Yifan Hong1deca4b2021-09-10 16:16:44 -0700654 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000655 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700656 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700657 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000658
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000659 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700660 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700661 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700662 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700663 });
Steven Moreland4198a122021-08-03 17:37:58 -0700664 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000665 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700666 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000667 break;
668 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700669 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000670 break;
671 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700672 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000673 break;
674 default:
675 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000676 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700677 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000678 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000679 }
Steven Morelandc1635952021-04-01 16:20:47 +0000680 return ret;
681 }
682
Steven Moreland4313d7e2021-07-15 23:41:22 +0000683 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000684 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700685 .proc = createRpcTestSocketServerProcess(
686 options,
687 [&](const sp<RpcServer>& server) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000688 server->setPerSessionRootObject([&](const void* addrPtr, size_t len) {
689 // UNIX sockets with abstract addresses return
690 // sizeof(sa_family_t)==2 in addrlen
691 CHECK_GE(len, sizeof(sa_family_t));
692 const sockaddr* addr = reinterpret_cast<const sockaddr*>(addrPtr);
Steven Moreland51c44a92021-10-14 16:50:35 -0700693 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
694 switch (addr->sa_family) {
695 case AF_UNIX:
696 // nothing to save
697 break;
698 case AF_VSOCK:
699 CHECK_EQ(len, sizeof(sockaddr_vm));
700 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
701 ->svm_port;
702 break;
703 case AF_INET:
704 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700705 service->port =
706 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
707 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700708 break;
709 case AF_INET6:
710 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700711 service->port =
712 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
713 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700714 break;
715 default:
716 LOG_ALWAYS_FATAL("Unrecognized address family %d",
717 addr->sa_family);
718 }
719 service->server = server;
720 return service;
721 });
722 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000723 };
724
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000725 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000726 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
727
728 return ret;
729 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700730
731 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
732 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000733};
734
Steven Morelandc1635952021-04-01 16:20:47 +0000735TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000736 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 ASSERT_NE(proc.rootBinder, nullptr);
738 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
739}
740
Steven Moreland4cf688f2021-03-31 01:48:58 +0000741TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000742 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000743 ASSERT_NE(proc.rootBinder, nullptr);
744 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
745}
746
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000748 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000749 for (auto session : proc.proc.sessions) {
750 ASSERT_NE(nullptr, session.root);
751 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000752 }
753}
754
Steven Moreland51c44a92021-10-14 16:50:35 -0700755TEST_P(BinderRpc, SeparateRootObject) {
756 SocketType type = std::get<0>(GetParam());
757 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
758 // we can't get port numbers for unix sockets
759 return;
760 }
761
762 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
763
764 int port1 = 0;
765 EXPECT_OK(proc.rootIface->getClientPort(&port1));
766
767 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
768 int port2;
769 EXPECT_OK(rootIface2->getClientPort(&port2));
770
771 // we should have a different IBinderRpcTest object created for each
772 // session, because we use setPerSessionRootObject
773 EXPECT_NE(port1, port2);
774}
775
Steven Morelandc1635952021-04-01 16:20:47 +0000776TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000777 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000778 Parcel data;
779 Parcel reply;
780 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
781}
782
Steven Moreland67753c32021-04-02 18:45:19 +0000783TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700784 auto proc1 = createRpcTestSocketServerProcess({});
785 auto proc2 = createRpcTestSocketServerProcess({});
786
787 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000788
789 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700790 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000791 p1.writeInt32(3);
792
Frederick Maylea4ed5672022-06-17 22:03:38 +0000793 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700794 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
795
Steven Moreland67753c32021-04-02 18:45:19 +0000796 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700797 p2.markForBinder(proc2.rootBinder);
798 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000799
800 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
801 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
802}
803
Steven Morelandc1635952021-04-01 16:20:47 +0000804TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000805 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 Parcel data;
807 data.markForBinder(proc.rootBinder);
808 Parcel reply;
809 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
810}
811
Steven Morelandc1635952021-04-01 16:20:47 +0000812TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000813 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000814 EXPECT_OK(proc.rootIface->sendString("asdf"));
815}
816
Steven Morelandc1635952021-04-01 16:20:47 +0000817TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000818 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 std::string doubled;
820 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
821 EXPECT_EQ("cool cool ", doubled);
822}
823
Steven Morelandc1635952021-04-01 16:20:47 +0000824TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000825 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000826 std::string single = std::string(1024, 'a');
827 std::string doubled;
828 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
829 EXPECT_EQ(single + single, doubled);
830}
831
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000832TEST_P(BinderRpc, InvalidNullBinderReturn) {
833 auto proc = createRpcTestSocketServerProcess({});
834
835 sp<IBinder> outBinder;
836 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
837}
838
Steven Morelandc1635952021-04-01 16:20:47 +0000839TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000840 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000841
842 int32_t pingResult;
843 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
844 EXPECT_EQ(OK, pingResult);
845
846 EXPECT_EQ(0, MyBinderRpcSession::gNum);
847}
848
Steven Morelandc1635952021-04-01 16:20:47 +0000849TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000850 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
853 sp<IBinder> outBinder;
854 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
855 EXPECT_EQ(inBinder, outBinder);
856
857 wp<IBinder> weak = inBinder;
858 inBinder = nullptr;
859 outBinder = nullptr;
860
861 // Force reading a reply, to process any pending dec refs from the other
862 // process (the other process will process dec refs there before processing
863 // the ping here).
864 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
865
866 EXPECT_EQ(nullptr, weak.promote());
867
868 EXPECT_EQ(0, MyBinderRpcSession::gNum);
869}
870
Steven Morelandc1635952021-04-01 16:20:47 +0000871TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000872 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000873
874 sp<IBinderRpcSession> session;
875 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
876
877 sp<IBinder> inBinder = IInterface::asBinder(session);
878 sp<IBinder> outBinder;
879 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
880 EXPECT_EQ(inBinder, outBinder);
881
882 wp<IBinder> weak = inBinder;
883 session = nullptr;
884 inBinder = nullptr;
885 outBinder = nullptr;
886
887 // Force reading a reply, to process any pending dec refs from the other
888 // process (the other process will process dec refs there before processing
889 // the ping here).
890 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
891
892 EXPECT_EQ(nullptr, weak.promote());
893}
894
Steven Morelandc1635952021-04-01 16:20:47 +0000895TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000896 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000897
898 sp<IBinder> outBinder;
899 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
900 EXPECT_EQ(nullptr, outBinder);
901}
902
Steven Morelandc1635952021-04-01 16:20:47 +0000903TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000904 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000905
906 IBinder* ptr = nullptr;
907 {
908 sp<IBinder> binder = new BBinder();
909 ptr = binder.get();
910 EXPECT_OK(proc.rootIface->holdBinder(binder));
911 }
912
913 sp<IBinder> held;
914 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
915
916 EXPECT_EQ(held.get(), ptr);
917
918 // stop holding binder, because we test to make sure references are cleaned
919 // up
920 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
921 // and flush ref counts
922 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
923}
924
925// START TESTS FOR LIMITATIONS OF SOCKET BINDER
926// These are behavioral differences form regular binder, where certain usecases
927// aren't supported.
928
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000929TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000930 auto proc1 = createRpcTestSocketServerProcess({});
931 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000932
933 sp<IBinder> outBinder;
934 EXPECT_EQ(INVALID_OPERATION,
935 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
936}
937
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000938TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000939 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000940
941 sp<IBinder> outBinder;
942 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000943 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000944 .transactionError());
945}
946
Steven Morelandc1635952021-04-01 16:20:47 +0000947TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000948 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000949
950 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
951 sp<IBinder> outBinder;
952 EXPECT_EQ(INVALID_OPERATION,
953 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
954}
955
Steven Morelandc1635952021-04-01 16:20:47 +0000956TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000957 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000958
959 // for historical reasons, IServiceManager interface only returns the
960 // exception code
961 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
962 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
963}
964
965// END TESTS FOR LIMITATIONS OF SOCKET BINDER
966
Steven Morelandc1635952021-04-01 16:20:47 +0000967TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000968 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000969
970 sp<IBinder> outBinder;
971 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
972 EXPECT_EQ(proc.rootBinder, outBinder);
973}
974
Steven Morelandc1635952021-04-01 16:20:47 +0000975TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000976 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000977
978 auto nastyNester = sp<MyBinderRpcTest>::make();
979 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
980
981 wp<IBinder> weak = nastyNester;
982 nastyNester = nullptr;
983 EXPECT_EQ(nullptr, weak.promote());
984}
985
Steven Morelandc1635952021-04-01 16:20:47 +0000986TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000987 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000988
989 sp<IBinder> a;
990 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
991
992 sp<IBinder> b;
993 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
994
995 EXPECT_EQ(a, b);
996}
997
Steven Morelandc1635952021-04-01 16:20:47 +0000998TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000999 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001000
1001 sp<IBinder> a;
1002 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
1003 wp<IBinder> weak = a;
1004 a = nullptr;
1005
1006 sp<IBinder> b;
1007 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
1008
1009 // this is the wrong behavior, since BpBinder
1010 // doesn't implement onIncStrongAttempted
1011 // but make sure there is no crash
1012 EXPECT_EQ(nullptr, weak.promote());
1013
1014 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
1015
1016 // In order to fix this:
1017 // - need to have incStrongAttempted reflected across IPC boundary (wait for
1018 // response to promote - round trip...)
1019 // - sendOnLastWeakRef, to delete entries out of RpcState table
1020 EXPECT_EQ(b, weak.promote());
1021}
1022
1023#define expectSessions(expected, iface) \
1024 do { \
1025 int session; \
1026 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
1027 EXPECT_EQ(expected, session); \
1028 } while (false)
1029
Steven Morelandc1635952021-04-01 16:20:47 +00001030TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001031 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001032
1033 sp<IBinderRpcSession> session;
1034 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
1035 std::string out;
1036 EXPECT_OK(session->getName(&out));
1037 EXPECT_EQ("aoeu", out);
1038
1039 expectSessions(1, proc.rootIface);
1040 session = nullptr;
1041 expectSessions(0, proc.rootIface);
1042}
1043
Steven Morelandc1635952021-04-01 16:20:47 +00001044TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001045 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001046
1047 std::vector<sp<IBinderRpcSession>> sessions;
1048
1049 for (size_t i = 0; i < 15; i++) {
1050 expectSessions(i, proc.rootIface);
1051 sp<IBinderRpcSession> session;
1052 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1053 sessions.push_back(session);
1054 }
1055 expectSessions(sessions.size(), proc.rootIface);
1056 for (size_t i = 0; i < sessions.size(); i++) {
1057 std::string out;
1058 EXPECT_OK(sessions.at(i)->getName(&out));
1059 EXPECT_EQ(std::to_string(i), out);
1060 }
1061 expectSessions(sessions.size(), proc.rootIface);
1062
1063 while (!sessions.empty()) {
1064 sessions.pop_back();
1065 expectSessions(sessions.size(), proc.rootIface);
1066 }
1067 expectSessions(0, proc.rootIface);
1068}
1069
1070size_t epochMillis() {
1071 using std::chrono::duration_cast;
1072 using std::chrono::milliseconds;
1073 using std::chrono::seconds;
1074 using std::chrono::system_clock;
1075 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1076}
1077
Steven Morelandc1635952021-04-01 16:20:47 +00001078TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001079 constexpr size_t kNumThreads = 10;
1080
Steven Moreland4313d7e2021-07-15 23:41:22 +00001081 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001082
1083 EXPECT_OK(proc.rootIface->lock());
1084
1085 // block all but one thread taking locks
1086 std::vector<std::thread> ts;
1087 for (size_t i = 0; i < kNumThreads - 1; i++) {
1088 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1089 }
1090
1091 usleep(100000); // give chance for calls on other threads
1092
1093 // other calls still work
1094 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1095
1096 constexpr size_t blockTimeMs = 500;
1097 size_t epochMsBefore = epochMillis();
1098 // after this, we should never see a response within this time
1099 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1100
1101 // this call should be blocked for blockTimeMs
1102 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1103
1104 size_t epochMsAfter = epochMillis();
1105 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1106
1107 for (auto& t : ts) t.join();
1108}
1109
Yifan Hong1f44f982021-10-08 17:16:47 -07001110void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1111 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001112 size_t epochMsBefore = epochMillis();
1113
1114 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001115 for (size_t i = 0; i < numCalls; i++) {
1116 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001117 }
1118
1119 for (auto& t : ts) t.join();
1120
1121 size_t epochMsAfter = epochMillis();
1122
Yifan Hong1f44f982021-10-08 17:16:47 -07001123 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001124
1125 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001126 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1127}
1128
1129TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1130 constexpr size_t kNumThreads = 10;
1131 constexpr size_t kNumCalls = kNumThreads + 3;
1132 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1133 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1134}
1135
1136TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1137 constexpr size_t kNumThreads = 20;
1138 constexpr size_t kNumOutgoingConnections = 10;
1139 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1140 auto proc = createRpcTestSocketServerProcess(
1141 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1142 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001143}
1144
Steven Morelandc1635952021-04-01 16:20:47 +00001145TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001146 constexpr size_t kNumClientThreads = 10;
1147 constexpr size_t kNumServerThreads = 10;
1148 constexpr size_t kNumCalls = 100;
1149
Steven Moreland4313d7e2021-07-15 23:41:22 +00001150 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001151
1152 std::vector<std::thread> threads;
1153 for (size_t i = 0; i < kNumClientThreads; i++) {
1154 threads.push_back(std::thread([&] {
1155 for (size_t j = 0; j < kNumCalls; j++) {
1156 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001157 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001158 EXPECT_EQ(proc.rootBinder, out);
1159 }
1160 }));
1161 }
1162
1163 for (auto& t : threads) t.join();
1164}
1165
Steven Moreland925ba0a2021-09-17 18:06:32 -07001166static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1167 std::vector<std::thread> threads;
1168 for (size_t i = 0; i < threadCount; i++) {
1169 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1170 }
1171 for (auto& t : threads) t.join();
1172}
1173
Steven Morelandc6046982021-04-20 00:49:42 +00001174TEST_P(BinderRpc, OnewayStressTest) {
1175 constexpr size_t kNumClientThreads = 10;
1176 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001177 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001178
Steven Moreland4313d7e2021-07-15 23:41:22 +00001179 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001180
1181 std::vector<std::thread> threads;
1182 for (size_t i = 0; i < kNumClientThreads; i++) {
1183 threads.push_back(std::thread([&] {
1184 for (size_t j = 0; j < kNumCalls; j++) {
1185 EXPECT_OK(proc.rootIface->sendString("a"));
1186 }
Steven Morelandc6046982021-04-20 00:49:42 +00001187 }));
1188 }
1189
1190 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001191
1192 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001193}
1194
Steven Morelandc1635952021-04-01 16:20:47 +00001195TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001196 constexpr size_t kReallyLongTimeMs = 100;
1197 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1198
Steven Moreland4313d7e2021-07-15 23:41:22 +00001199 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001200
1201 size_t epochMsBefore = epochMillis();
1202
1203 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1204
1205 size_t epochMsAfter = epochMillis();
1206 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1207}
1208
Steven Morelandc1635952021-04-01 16:20:47 +00001209TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001210 constexpr size_t kNumSleeps = 10;
1211 constexpr size_t kNumExtraServerThreads = 4;
1212 constexpr size_t kSleepMs = 50;
1213
1214 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001215 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001216
1217 EXPECT_OK(proc.rootIface->lock());
1218
Steven Moreland1c678802021-09-17 16:48:47 -07001219 size_t epochMsBefore = epochMillis();
1220
1221 // all these *Async commands should be queued on the server sequentially,
1222 // even though there are multiple threads.
1223 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001224 proc.rootIface->sleepMsAsync(kSleepMs);
1225 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001226 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1227
Steven Moreland1c678802021-09-17 16:48:47 -07001228 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001229 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001230
Steven Moreland5553ac42020-11-11 02:14:45 +00001231 size_t epochMsAfter = epochMillis();
1232
1233 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001234
Steven Moreland925ba0a2021-09-17 18:06:32 -07001235 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001236}
1237
Steven Morelandd45be622021-06-04 02:19:37 +00001238TEST_P(BinderRpc, OnewayCallExhaustion) {
1239 constexpr size_t kNumClients = 2;
1240 constexpr size_t kTooLongMs = 1000;
1241
Steven Moreland4313d7e2021-07-15 23:41:22 +00001242 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001243
1244 // Build up oneway calls on the second session to make sure it terminates
1245 // and shuts down. The first session should be unaffected (proc destructor
1246 // checks the first session).
1247 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1248
1249 std::vector<std::thread> threads;
1250 for (size_t i = 0; i < kNumClients; i++) {
1251 // one of these threads will get stuck queueing a transaction once the
1252 // socket fills up, the other will be able to fill up transactions on
1253 // this object
1254 threads.push_back(std::thread([&] {
1255 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1256 }
1257 }));
1258 }
1259 for (auto& t : threads) t.join();
1260
1261 Status status = iface->sleepMsAsync(kTooLongMs);
1262 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1263
Steven Moreland798e0d12021-07-14 23:19:25 +00001264 // now that it has died, wait for the remote session to shutdown
1265 std::vector<int32_t> remoteCounts;
1266 do {
1267 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1268 } while (remoteCounts.size() == kNumClients);
1269
Steven Morelandd45be622021-06-04 02:19:37 +00001270 // the second session should be shutdown in the other process by the time we
1271 // are able to join above (it'll only be hung up once it finishes processing
1272 // any pending commands). We need to erase this session from the record
1273 // here, so that the destructor for our session won't check that this
1274 // session is valid, but we still want it to test the other session.
1275 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1276}
1277
Steven Moreland659416d2021-05-11 00:47:50 +00001278TEST_P(BinderRpc, Callbacks) {
1279 const static std::string kTestString = "good afternoon!";
1280
Steven Morelandc7d40132021-06-10 03:42:11 +00001281 for (bool callIsOneway : {true, false}) {
1282 for (bool callbackIsOneway : {true, false}) {
1283 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001284 auto proc = createRpcTestSocketServerProcess(
1285 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001286 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001287
Steven Morelandc7d40132021-06-10 03:42:11 +00001288 if (callIsOneway) {
1289 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1290 kTestString));
1291 } else {
1292 EXPECT_OK(
1293 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1294 }
Steven Moreland659416d2021-05-11 00:47:50 +00001295
Steven Moreland03ecce62022-05-13 23:22:05 +00001296 // if both transactions are synchronous and the response is sent back on the
1297 // same thread, everything should have happened in a nested call. Otherwise,
1298 // the callback will be processed on another thread.
1299 if (callIsOneway || callbackIsOneway || delayed) {
1300 using std::literals::chrono_literals::operator""s;
1301 std::unique_lock<std::mutex> _l(cb->mMutex);
1302 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1303 }
Steven Moreland659416d2021-05-11 00:47:50 +00001304
Steven Morelandc7d40132021-06-10 03:42:11 +00001305 EXPECT_EQ(cb->mValues.size(), 1)
1306 << "callIsOneway: " << callIsOneway
1307 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1308 if (cb->mValues.empty()) continue;
1309 EXPECT_EQ(cb->mValues.at(0), kTestString)
1310 << "callIsOneway: " << callIsOneway
1311 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001312
Steven Morelandc7d40132021-06-10 03:42:11 +00001313 // since we are severing the connection, we need to go ahead and
1314 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001315 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1316 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1317 }
Steven Moreland659416d2021-05-11 00:47:50 +00001318
Steven Moreland1b304292021-07-15 22:59:34 +00001319 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001320 // need to manually shut it down
1321 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001322
Frederick Maylea12b0962022-06-25 01:13:22 +00001323 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1324 // Flaky. Sometimes gets SIGABRT.
1325 EXPECT_TRUE((WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0) ||
1326 (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT))
1327 << "server process failed: " << WaitStatusToString(wstatus);
1328 });
Steven Morelandc7d40132021-06-10 03:42:11 +00001329 proc.expectAlreadyShutdown = true;
1330 }
Steven Moreland659416d2021-05-11 00:47:50 +00001331 }
1332 }
1333}
1334
Steven Moreland195edb82021-06-08 02:44:39 +00001335TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001336 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001337 auto cb = sp<MyBinderRpcCallback>::make();
1338
1339 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1340 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1341}
1342
Steven Morelandc1635952021-04-01 16:20:47 +00001343TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001344 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001345 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001346
1347 // make sure there is some state during crash
1348 // 1. we hold their binder
1349 sp<IBinderRpcSession> session;
1350 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1351 // 2. they hold our binder
1352 sp<IBinder> binder = new BBinder();
1353 EXPECT_OK(proc.rootIface->holdBinder(binder));
1354
1355 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1356 << "Do death cleanup: " << doDeathCleanup;
1357
Frederick Maylea12b0962022-06-25 01:13:22 +00001358 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1359 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1360 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1361 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001362 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001363 }
1364}
1365
Steven Morelandd7302072021-05-15 01:32:04 +00001366TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Morelanda83191d2021-10-27 10:14:53 -07001367 bool okToFork = ProcessState::selfOrNull() == nullptr;
1368
Steven Moreland4313d7e2021-07-15 23:41:22 +00001369 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001370
Steven Morelanda83191d2021-10-27 10:14:53 -07001371 // If this process has used ProcessState already, then the forked process
1372 // cannot use it at all. If this process hasn't used it (depending on the
1373 // order tests are run), then the forked process can use it, and we'll only
1374 // catch the invalid usage the second time. Such is the burden of global
1375 // state!
1376 if (okToFork) {
1377 // we can't allocate IPCThreadState so actually the first time should
1378 // succeed :(
1379 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1380 }
Steven Morelandd7302072021-05-15 01:32:04 +00001381
1382 // second time! we catch the error :)
1383 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1384
Frederick Maylea12b0962022-06-25 01:13:22 +00001385 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1386 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1387 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1388 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001389 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001390}
1391
Steven Moreland37aff182021-03-26 02:04:16 +00001392TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001393 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001394
1395 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1396 ASSERT_NE(binder, nullptr);
1397
1398 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1399}
1400
1401TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001402 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001403
1404 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1405 ASSERT_NE(binder, nullptr);
1406
1407 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1408 ASSERT_NE(ndkBinder, nullptr);
1409
1410 std::string out;
1411 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1412 ASSERT_TRUE(status.isOk()) << status.getDescription();
1413 ASSERT_EQ("aoeuaoeu", out);
1414}
1415
Steven Moreland5553ac42020-11-11 02:14:45 +00001416ssize_t countFds() {
1417 DIR* dir = opendir("/proc/self/fd/");
1418 if (dir == nullptr) return -1;
1419 ssize_t ret = 0;
1420 dirent* ent;
1421 while ((ent = readdir(dir)) != nullptr) ret++;
1422 closedir(dir);
1423 return ret;
1424}
1425
Steven Morelandc1635952021-04-01 16:20:47 +00001426TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001427 ssize_t beforeFds = countFds();
1428 ASSERT_GE(beforeFds, 0);
1429 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001430 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001431 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1432 }
1433 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1434}
1435
Devin Moore800b2252021-10-15 16:22:57 +00001436TEST_P(BinderRpc, AidlDelegatorTest) {
1437 auto proc = createRpcTestSocketServerProcess({});
1438 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1439 ASSERT_NE(nullptr, myDelegator);
1440
1441 std::string doubled;
1442 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1443 EXPECT_EQ("cool cool ", doubled);
1444}
1445
Steven Morelandda573042021-06-12 01:13:45 +00001446static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001447 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001448 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001449 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001450 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1451 if (status == -EAFNOSUPPORT) {
1452 return false;
1453 }
1454 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1455 }
Steven Morelandda573042021-06-12 01:13:45 +00001456 server->start();
1457
Yifan Hongfdd9f692021-09-09 15:12:52 -07001458 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001459 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001460 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001461 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1462 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001463}
1464
Yifan Hong1deca4b2021-09-10 16:16:44 -07001465static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1466 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1467
1468 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001469
1470 static bool hasVsockLoopback = testSupportVsockLoopback();
1471
1472 if (hasVsockLoopback) {
1473 ret.push_back(SocketType::VSOCK);
1474 }
1475
1476 return ret;
1477}
1478
Frederick Mayledc07cf82022-05-26 20:30:12 +00001479static std::vector<uint32_t> testVersions() {
1480 std::vector<uint32_t> versions;
1481 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1482 versions.push_back(i);
1483 }
1484 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1485 return versions;
1486}
1487
Yifan Hong702115c2021-06-24 15:39:18 -07001488INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1489 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001490 ::testing::ValuesIn(RpcSecurityValues()),
1491 ::testing::ValuesIn(testVersions()),
1492 ::testing::ValuesIn(testVersions())),
Yifan Hong702115c2021-06-24 15:39:18 -07001493 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001494
Yifan Hong702115c2021-06-24 15:39:18 -07001495class BinderRpcServerRootObject
1496 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001497
1498TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1499 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1500 auto setRootObject = [](bool isStrong) -> SetFn {
1501 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1502 };
1503
Yifan Hong702115c2021-06-24 15:39:18 -07001504 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1505 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001506 auto binder1 = sp<BBinder>::make();
1507 IBinder* binderRaw1 = binder1.get();
1508 setRootObject(isStrong1)(server.get(), binder1);
1509 EXPECT_EQ(binderRaw1, server->getRootObject());
1510 binder1.clear();
1511 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1512
1513 auto binder2 = sp<BBinder>::make();
1514 IBinder* binderRaw2 = binder2.get();
1515 setRootObject(isStrong2)(server.get(), binder2);
1516 EXPECT_EQ(binderRaw2, server->getRootObject());
1517 binder2.clear();
1518 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1519}
1520
1521INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001522 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1523 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001524
Yifan Hong1a235852021-05-13 16:07:47 -07001525class OneOffSignal {
1526public:
1527 // If notify() was previously called, or is called within |duration|, return true; else false.
1528 template <typename R, typename P>
1529 bool wait(std::chrono::duration<R, P> duration) {
1530 std::unique_lock<std::mutex> lock(mMutex);
1531 return mCv.wait_for(lock, duration, [this] { return mValue; });
1532 }
1533 void notify() {
1534 std::unique_lock<std::mutex> lock(mMutex);
1535 mValue = true;
1536 lock.unlock();
1537 mCv.notify_all();
1538 }
1539
1540private:
1541 std::mutex mMutex;
1542 std::condition_variable mCv;
1543 bool mValue = false;
1544};
1545
Frederick Mayledc07cf82022-05-26 20:30:12 +00001546TEST_P(BinderRpcServerOnly, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001547 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001548 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1549 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001550 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001551 auto joinEnds = std::make_shared<OneOffSignal>();
1552
1553 // If things are broken and the thread never stops, don't block other tests. Because the thread
1554 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1555 // shared pointers are passed.
1556 std::thread([server, joinEnds] {
1557 server->join();
1558 joinEnds->notify();
1559 }).detach();
1560
1561 bool shutdown = false;
1562 for (int i = 0; i < 10 && !shutdown; i++) {
1563 usleep(300 * 1000); // 300ms; total 3s
1564 if (server->shutdown()) shutdown = true;
1565 }
1566 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1567
1568 ASSERT_TRUE(joinEnds->wait(2s))
1569 << "After server->shutdown() returns true, join() did not stop after 2s";
1570}
1571
Yifan Hong194acf22021-06-29 18:44:56 -07001572TEST(BinderRpc, Java) {
1573#if !defined(__ANDROID__)
1574 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1575 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1576 "to binderHostDeviceTest. Hence, just disable this test on host.";
1577#endif // !__ANDROID__
1578 sp<IServiceManager> sm = defaultServiceManager();
1579 ASSERT_NE(nullptr, sm);
1580 // Any Java service with non-empty getInterfaceDescriptor() would do.
1581 // Let's pick batteryproperties.
1582 auto binder = sm->checkService(String16("batteryproperties"));
1583 ASSERT_NE(nullptr, binder);
1584 auto descriptor = binder->getInterfaceDescriptor();
1585 ASSERT_GE(descriptor.size(), 0);
1586 ASSERT_EQ(OK, binder->pingBinder());
1587
1588 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001589 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001590 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001591 auto socket = rpcServer->releaseServer();
1592
1593 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001594 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1595
Yifan Honge3caaf22022-01-12 14:46:56 -08001596 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1597 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001598 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001599 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1600 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001601 << statusToString(setRpcClientDebugStatus);
1602 GTEST_SKIP();
1603 }
1604
1605 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001606
1607 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001608 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001609 auto rpcBinder = rpcSession->getRootObject();
1610 ASSERT_NE(nullptr, rpcBinder);
1611
1612 ASSERT_EQ(OK, rpcBinder->pingBinder());
1613
1614 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1615 << "getInterfaceDescriptor should not crash system_server";
1616 ASSERT_EQ(OK, rpcBinder->pingBinder());
1617}
1618
Frederick Mayledc07cf82022-05-26 20:30:12 +00001619INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1620 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1621 ::testing::ValuesIn(testVersions())),
1622 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001623
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001624class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001626 // Only parameterized only server version because `RpcSession` is bypassed
1627 // in the client half of the tests.
1628 using Param =
1629 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001631
1632 // A server that handles client socket connections.
1633 class Server {
1634 public:
1635 explicit Server() {}
1636 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001637 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001638 [[nodiscard]] AssertionResult setUp(
1639 const Param& param,
1640 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001641 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001643 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001644 switch (socketType) {
1645 case SocketType::PRECONNECTED: {
1646 return AssertionFailure() << "Not supported by this test";
1647 } break;
1648 case SocketType::UNIX: {
1649 auto addr = allocateSocketAddress();
1650 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1651 if (status != OK) {
1652 return AssertionFailure()
1653 << "setupUnixDomainServer: " << statusToString(status);
1654 }
1655 mConnectToServer = [addr] {
1656 return connectTo(UnixSocketAddress(addr.c_str()));
1657 };
1658 } break;
1659 case SocketType::VSOCK: {
1660 auto port = allocateVsockPort();
1661 auto status = rpcServer->setupVsockServer(port);
1662 if (status != OK) {
1663 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1664 }
1665 mConnectToServer = [port] {
1666 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1667 };
1668 } break;
1669 case SocketType::INET: {
1670 unsigned int port;
1671 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1672 if (status != OK) {
1673 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1674 }
1675 mConnectToServer = [port] {
1676 const char* addr = kLocalInetAddress;
1677 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1678 if (aiStart == nullptr) return base::unique_fd{};
1679 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1680 auto fd = connectTo(
1681 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1682 if (fd.ok()) return fd;
1683 }
1684 ALOGE("None of the socket address resolved for %s:%u can be connected",
1685 addr, port);
1686 return base::unique_fd{};
1687 };
1688 }
1689 }
1690 mFd = rpcServer->releaseServer();
1691 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001692 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001693 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1694 mSetup = true;
1695 return AssertionSuccess();
1696 }
1697 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1698 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1699 return mCertVerifier;
1700 }
1701 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1702 void start() {
1703 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1704 mThread = std::make_unique<std::thread>(&Server::run, this);
1705 }
1706 void run() {
1707 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1708
1709 std::vector<std::thread> threads;
1710 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1711 base::unique_fd acceptedFd(
1712 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1713 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1714 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1715 }
1716
1717 for (auto& thread : threads) thread.join();
1718 }
1719 void handleOne(android::base::unique_fd acceptedFd) {
1720 ASSERT_TRUE(acceptedFd.ok());
1721 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1722 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001723 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724 }
Yifan Honge07d2732021-09-13 21:59:14 -07001725 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001726 shutdown();
1727 join();
1728 }
1729 void shutdown() { mFdTrigger->trigger(); }
1730
1731 void setPostConnect(
1732 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1733 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001734 }
1735
1736 private:
1737 std::unique_ptr<std::thread> mThread;
1738 ConnectToServer mConnectToServer;
1739 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1740 base::unique_fd mFd;
1741 std::unique_ptr<RpcTransportCtx> mCtx;
1742 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1743 std::make_shared<RpcCertificateVerifierSimple>();
1744 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001745 // The function invoked after connection and handshake. By default, it is
1746 // |defaultPostConnect| that sends |kMessage| to the client.
1747 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1748 Server::defaultPostConnect;
1749
1750 void join() {
1751 if (mThread != nullptr) {
1752 mThread->join();
1753 mThread = nullptr;
1754 }
1755 }
1756
1757 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1758 FdTrigger* fdTrigger) {
1759 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001760 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001761 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1762 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001763 if (status != OK) return AssertionFailure() << statusToString(status);
1764 return AssertionSuccess();
1765 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001766 };
1767
1768 class Client {
1769 public:
1770 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1771 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001772 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001773 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1774 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001775 mFdTrigger = FdTrigger::make();
1776 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1777 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1778 return AssertionSuccess();
1779 }
1780 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1781 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1782 return mCertVerifier;
1783 }
Yifan Hong67519322021-09-13 18:51:16 -07001784 // connect() and do handshake
1785 bool setUpTransport() {
1786 mFd = mConnectToServer();
1787 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1788 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1789 return mClientTransport != nullptr;
1790 }
1791 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1792 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1793 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001794 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001795 status_t readStatus =
1796 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
1797 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001798 if (readStatus != OK) {
1799 return AssertionFailure() << statusToString(readStatus);
1800 }
1801 if (readMessage != expectedMessage) {
1802 return AssertionFailure()
1803 << "Expected " << expectedMessage << ", actual " << readMessage;
1804 }
1805 return AssertionSuccess();
1806 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001807 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001808 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001809 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1810 return;
1811 }
1812 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001813 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001814 }
1815
1816 private:
1817 ConnectToServer mConnectToServer;
1818 base::unique_fd mFd;
1819 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1820 std::unique_ptr<RpcTransportCtx> mCtx;
1821 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1822 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001823 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824 };
1825
1826 // Make A trust B.
1827 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001828 static status_t trust(RpcSecurity rpcSecurity,
1829 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1830 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001832 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1833 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1834 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001835 }
1836
1837 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001838};
1839
1840class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1841public:
1842 using Server = RpcTransportTestUtils::Server;
1843 using Client = RpcTransportTestUtils::Client;
1844 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001845 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001846 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1847 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001848 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 return ret;
1850 }
1851 static std::vector<ParamType> getRpcTranportTestParams() {
1852 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001853 for (auto serverVersion : testVersions()) {
1854 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1855 for (auto rpcSecurity : RpcSecurityValues()) {
1856 switch (rpcSecurity) {
1857 case RpcSecurity::RAW: {
1858 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1859 } break;
1860 case RpcSecurity::TLS: {
1861 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1862 serverVersion);
1863 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1864 serverVersion);
1865 } break;
1866 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 }
1868 }
1869 }
1870 return ret;
1871 }
1872 template <typename A, typename B>
1873 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001874 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1875 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001876 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1877 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001878};
1879
1880TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001881 auto server = std::make_unique<Server>();
1882 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001883
1884 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001885 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001886
1887 ASSERT_EQ(OK, trust(&client, server));
1888 ASSERT_EQ(OK, trust(server, &client));
1889
1890 server->start();
1891 client.run();
1892}
1893
1894TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001895 auto server = std::make_unique<Server>();
1896 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001897
1898 std::vector<Client> clients;
1899 for (int i = 0; i < 2; i++) {
1900 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001901 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902 ASSERT_EQ(OK, trust(&client, server));
1903 ASSERT_EQ(OK, trust(server, &client));
1904 }
1905
1906 server->start();
1907 for (auto& client : clients) client.run();
1908}
1909
1910TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001911 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1912 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001913
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001914 auto untrustedServer = std::make_unique<Server>();
1915 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001916
1917 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001918 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001919
1920 ASSERT_EQ(OK, trust(untrustedServer, &client));
1921
1922 untrustedServer->start();
1923
1924 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1925 // the client can't verify the server's identity.
1926 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1927 client.run(handshakeOk);
1928}
1929TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001930 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1931 (void)serverVersion;
1932
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001933 auto validServer = std::make_unique<Server>();
1934 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001935
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936 auto maliciousServer = std::make_unique<Server>();
1937 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001938
1939 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001940 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001941
1942 ASSERT_EQ(OK, trust(&client, validServer));
1943 ASSERT_EQ(OK, trust(validServer, &client));
1944 ASSERT_EQ(OK, trust(maliciousServer, &client));
1945
1946 maliciousServer->start();
1947
1948 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1949 // the client can't verify the server's identity.
1950 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1951 client.run(handshakeOk);
1952}
1953
1954TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001955 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1956 (void)serverVersion;
1957
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001958 auto server = std::make_unique<Server>();
1959 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001960
1961 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001962 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001963
1964 ASSERT_EQ(OK, trust(&client, server));
1965
1966 server->start();
1967
1968 // For TLS, Client should be able to verify server's identity, so client should see
1969 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1970 // identity and should drop the connection, so client shouldn't be able to read anything.
1971 bool readOk = rpcSecurity != RpcSecurity::TLS;
1972 client.run(true, readOk);
1973}
1974
1975TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001976 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1977 (void)serverVersion;
1978
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001979 auto server = std::make_unique<Server>();
1980 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001981
1982 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001983 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001984 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001985 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001986
1987 ASSERT_EQ(OK, trust(&validClient, server));
1988 ASSERT_EQ(OK, trust(&maliciousClient, server));
1989
1990 server->start();
1991
1992 // See UntrustedClient.
1993 bool readOk = rpcSecurity != RpcSecurity::TLS;
1994 maliciousClient.run(true, readOk);
1995}
1996
Yifan Hong67519322021-09-13 18:51:16 -07001997TEST_P(RpcTransportTest, Trigger) {
1998 std::string msg2 = ", world!";
1999 std::mutex writeMutex;
2000 std::condition_variable writeCv;
2001 bool shouldContinueWriting = false;
2002 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002003 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002004 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002005 auto status =
2006 serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07002007 if (status != OK) return AssertionFailure() << statusToString(status);
2008
2009 {
2010 std::unique_lock<std::mutex> lock(writeMutex);
2011 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2012 return AssertionFailure() << "write barrier not cleared in time!";
2013 }
2014 }
2015
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002016 iovec msg2Iov{msg2.data(), msg2.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002017 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt);
Steven Morelandc591b472021-09-16 13:56:11 -07002018 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002019 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002020 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002021 << statusToString(status);
2022 return AssertionSuccess();
2023 };
2024
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025 auto server = std::make_unique<Server>();
2026 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002027
2028 // Set up client
2029 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002030 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002031
2032 // Exchange keys
2033 ASSERT_EQ(OK, trust(&client, server));
2034 ASSERT_EQ(OK, trust(server, &client));
2035
2036 server->setPostConnect(serverPostConnect);
2037
Yifan Hong67519322021-09-13 18:51:16 -07002038 server->start();
2039 // connect() to server and do handshake
2040 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002041 // read the first message. This ensures that server has finished handshake and start handling
2042 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002043 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002044 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2045 // write is on an FdTrigger that has been shut down.
2046 server->shutdown();
2047 // Continues server thread to write the second message.
2048 {
Yifan Hong22211f82021-09-14 12:32:25 -07002049 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002050 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002051 }
Yifan Hong22211f82021-09-14 12:32:25 -07002052 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002053 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002054 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002055 // On the client side, second read fails with DEAD_OBJECT
2056 ASSERT_FALSE(client.readMessage(msg2));
2057}
2058
Yifan Hong1deca4b2021-09-10 16:16:44 -07002059INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002060 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002061 RpcTransportTest::PrintParamInfo);
2062
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002063class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002064 : public testing::TestWithParam<
2065 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002066public:
2067 template <typename A, typename B>
2068 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002069 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2070 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002071 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2072 }
2073 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002074 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2075 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2076 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002077 };
2078};
2079
2080TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002081 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002082
2083 std::vector<uint8_t> pkeyData, certData;
2084 {
2085 auto pkey = makeKeyPairForSelfSignedCert();
2086 ASSERT_NE(nullptr, pkey);
2087 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2088 ASSERT_NE(nullptr, cert);
2089 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2090 certData = serializeCertificate(cert.get(), certificateFormat);
2091 }
2092
2093 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2094 auto desCert = deserializeCertificate(certData, certificateFormat);
2095 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002096 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2097 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002098
2099 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2100 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2101
2102 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2103 ASSERT_TRUE(client.setUp(utilsParam));
2104
2105 ASSERT_EQ(OK, trust(&client, server));
2106 ASSERT_EQ(OK, trust(server, &client));
2107
2108 server->start();
2109 client.run();
2110}
2111
2112INSTANTIATE_TEST_CASE_P(
2113 BinderRpc, RpcTransportTlsKeyTest,
2114 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2115 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002116 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2117 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002118 RpcTransportTlsKeyTest::PrintParamInfo);
2119
Steven Morelandc1635952021-04-01 16:20:47 +00002120} // namespace android
2121
2122int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002123 ::testing::InitGoogleTest(&argc, argv);
2124 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002125
Steven Moreland5553ac42020-11-11 02:14:45 +00002126 return RUN_ALL_TESTS();
2127}