blob: 51614698a0f12e1b943950295052523a93079721 [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>
Steven Moreland37aff182021-03-26 02:04:16 +000026#include <android/binder_auto_utils.h>
27#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/Binder.h>
29#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000030#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000031#include <binder/IServiceManager.h>
32#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/RpcSession.h>
Yifan Honge0e53282021-09-23 18:37:21 -070035#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070036#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070037#include <binder/RpcTransport.h>
38#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070039#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000040#include <gtest/gtest.h>
41
Steven Morelandc1635952021-04-01 16:20:47 +000042#include <chrono>
43#include <cstdlib>
44#include <iostream>
45#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000046#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000047
Yifan Hong1deca4b2021-09-10 16:16:44 -070048#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000049#include <sys/prctl.h>
50#include <unistd.h>
51
Yifan Hong1deca4b2021-09-10 16:16:44 -070052#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070053#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070054#include "../RpcState.h" // for debugging
55#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000056
Yifan Hong1a235852021-05-13 16:07:47 -070057using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070058using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070059using testing::AssertionFailure;
60using testing::AssertionResult;
61using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070062
Steven Moreland5553ac42020-11-11 02:14:45 +000063namespace android {
64
Steven Morelandbf57bce2021-07-26 15:26:12 -070065static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
66 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000067const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070068
Yifan Hong92409752021-07-30 21:25:32 -070069enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070070
71static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070072 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070073}
74
Yifan Hong13c90062021-09-09 14:59:53 -070075static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070076 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
77 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070078 switch (rpcSecurity) {
79 case RpcSecurity::RAW:
80 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070081 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070082 if (verifier == nullptr) {
83 verifier = std::make_shared<RpcCertificateVerifierSimple>();
84 }
Yifan Hongffdaf952021-09-17 18:08:38 -070085 if (auth == nullptr) {
86 auth = std::make_unique<RpcAuthSelfSigned>();
87 }
88 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -070089 }
Yifan Hong702115c2021-06-24 15:39:18 -070090 default:
91 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
92 }
93}
94
Steven Moreland1fda67b2021-04-02 18:35:50 +000095TEST(BinderRpcParcel, EntireParcelFormatted) {
96 Parcel p;
97 p.writeInt32(3);
98
99 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
100}
101
Frederick Mayledc07cf82022-05-26 20:30:12 +0000102class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -0700103public:
104 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000105 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
106 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -0700107 }
108};
109
Frederick Mayledc07cf82022-05-26 20:30:12 +0000110TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700111 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
112 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +0000113 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
114 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700115 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700116 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700117 ASSERT_TRUE(server->hasServer());
118 base::unique_fd retrieved = server->releaseServer();
119 ASSERT_FALSE(server->hasServer());
120 ASSERT_EQ(sinkFd, retrieved.get());
121}
122
Steven Morelandbf57bce2021-07-26 15:26:12 -0700123TEST(BinderRpc, CannotUseNextWireVersion) {
124 auto session = RpcSession::make();
125 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
126 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
127 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
128 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
129}
130
131TEST(BinderRpc, CanUseExperimentalWireVersion) {
132 auto session = RpcSession::make();
133 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
134}
135
Steven Moreland5553ac42020-11-11 02:14:45 +0000136using android::binder::Status;
137
138#define EXPECT_OK(status) \
139 do { \
140 Status stat = (status); \
141 EXPECT_TRUE(stat.isOk()) << stat; \
142 } while (false)
143
144class MyBinderRpcSession : public BnBinderRpcSession {
145public:
146 static std::atomic<int32_t> gNum;
147
148 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
149 Status getName(std::string* name) override {
150 *name = mName;
151 return Status::ok();
152 }
153 ~MyBinderRpcSession() { gNum--; }
154
155private:
156 std::string mName;
157};
158std::atomic<int32_t> MyBinderRpcSession::gNum;
159
Steven Moreland659416d2021-05-11 00:47:50 +0000160class MyBinderRpcCallback : public BnBinderRpcCallback {
161 Status sendCallback(const std::string& value) {
162 std::unique_lock _l(mMutex);
163 mValues.push_back(value);
164 _l.unlock();
165 mCv.notify_one();
166 return Status::ok();
167 }
168 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
169
170public:
171 std::mutex mMutex;
172 std::condition_variable mCv;
173 std::vector<std::string> mValues;
174};
175
Steven Moreland5553ac42020-11-11 02:14:45 +0000176class MyBinderRpcTest : public BnBinderRpcTest {
177public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000178 wp<RpcServer> server;
Steven Moreland51c44a92021-10-14 16:50:35 -0700179 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000180
181 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000182 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 return Status::ok();
184 }
185 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000186 *strstr = str + str;
187 return Status::ok();
188 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700189 Status getClientPort(int* out) override {
190 *out = port;
191 return Status::ok();
192 }
Steven Moreland736664b2021-05-01 04:27:25 +0000193 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000194 sp<RpcServer> spServer = server.promote();
195 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
197 }
Steven Moreland736664b2021-05-01 04:27:25 +0000198 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199 for (auto session : spServer->listSessions()) {
200 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000201 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000202 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000203 return Status::ok();
204 }
205 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
206 if (binder == nullptr) {
207 std::cout << "Received null binder!" << std::endl;
208 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
209 }
210 *out = binder->pingBinder();
211 return Status::ok();
212 }
213 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
214 *out = binder;
215 return Status::ok();
216 }
217 static sp<IBinder> mHeldBinder;
218 Status holdBinder(const sp<IBinder>& binder) override {
219 mHeldBinder = binder;
220 return Status::ok();
221 }
222 Status getHeldBinder(sp<IBinder>* held) override {
223 *held = mHeldBinder;
224 return Status::ok();
225 }
226 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
227 if (count <= 0) return Status::ok();
228 return binder->nestMe(this, count - 1);
229 }
230 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
231 static sp<IBinder> binder = new BBinder;
232 *out = binder;
233 return Status::ok();
234 }
235 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
236 *out = new MyBinderRpcSession(name);
237 return Status::ok();
238 }
239 Status getNumOpenSessions(int32_t* out) override {
240 *out = MyBinderRpcSession::gNum;
241 return Status::ok();
242 }
243
244 std::mutex blockMutex;
245 Status lock() override {
246 blockMutex.lock();
247 return Status::ok();
248 }
249 Status unlockInMsAsync(int32_t ms) override {
250 usleep(ms * 1000);
251 blockMutex.unlock();
252 return Status::ok();
253 }
254 Status lockUnlock() override {
255 std::lock_guard<std::mutex> _l(blockMutex);
256 return Status::ok();
257 }
258
259 Status sleepMs(int32_t ms) override {
260 usleep(ms * 1000);
261 return Status::ok();
262 }
263
264 Status sleepMsAsync(int32_t ms) override {
265 // In-process binder calls are asynchronous, but the call to this method
266 // is synchronous wrt its client. This in/out-process threading model
267 // diffentiation is a classic binder leaky abstraction (for better or
268 // worse) and is preserved here the way binder sockets plugs itself
269 // into BpBinder, as nothing is changed at the higher levels
270 // (IInterface) which result in this behavior.
271 return sleepMs(ms);
272 }
273
Steven Moreland659416d2021-05-11 00:47:50 +0000274 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
275 const std::string& value) override {
276 if (callback == nullptr) {
277 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
278 }
279
280 if (delayed) {
281 std::thread([=]() {
282 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000283 Status status = doCallback(callback, oneway, false, value);
284 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000285 }).detach();
286 return Status::ok();
287 }
288
289 if (oneway) {
290 return callback->sendOnewayCallback(value);
291 }
292
293 return callback->sendCallback(value);
294 }
295
Steven Morelandc7d40132021-06-10 03:42:11 +0000296 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
297 const std::string& value) override {
298 return doCallback(callback, oneway, delayed, value);
299 }
300
Steven Moreland5553ac42020-11-11 02:14:45 +0000301 Status die(bool cleanup) override {
302 if (cleanup) {
303 exit(1);
304 } else {
305 _exit(1);
306 }
307 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000308
309 Status scheduleShutdown() override {
310 sp<RpcServer> strongServer = server.promote();
311 if (strongServer == nullptr) {
312 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
313 }
314 std::thread([=] {
315 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
316 }).detach();
317 return Status::ok();
318 }
319
Steven Morelandd7302072021-05-15 01:32:04 +0000320 Status useKernelBinderCallingId() override {
321 // this is WRONG! It does not make sense when using RPC binder, and
322 // because it is SO wrong, and so much code calls this, it should abort!
323
324 (void)IPCThreadState::self()->getCallingPid();
325 return Status::ok();
326 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000327};
328sp<IBinder> MyBinderRpcTest::mHeldBinder;
329
330class Process {
331public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700332 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700333 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
334 android::base::borrowed_fd /* readEnd */)>& f) {
335 android::base::unique_fd childWriteEnd;
336 android::base::unique_fd childReadEnd;
337 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
338 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 if (0 == (mPid = fork())) {
340 // racey: assume parent doesn't crash before this is set
341 prctl(PR_SET_PDEATHSIG, SIGHUP);
342
Yifan Hong1deca4b2021-09-10 16:16:44 -0700343 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000344
345 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000346 }
347 }
348 ~Process() {
349 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000350 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000351 }
352 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700353 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700354 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000355
356private:
357 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700358 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700359 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000360};
361
362static std::string allocateSocketAddress() {
363 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000364 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700365 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
366 unlink(ret.c_str());
367 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000368};
369
Steven Morelandda573042021-06-12 01:13:45 +0000370static unsigned int allocateVsockPort() {
371 static unsigned int vsockPort = 3456;
372 return vsockPort++;
373}
374
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000375struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000376 // reference to process hosting a socket server
377 Process host;
378
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 struct SessionInfo {
380 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000381 sp<IBinder> root;
382 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000383
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000384 // client session objects associated with other process
385 // each one represents a separate session
386 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000387
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000388 ProcessSession(ProcessSession&&) = default;
389 ~ProcessSession() {
390 for (auto& session : sessions) {
391 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000392 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000393
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 for (auto& info : sessions) {
395 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000396
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397 EXPECT_NE(nullptr, session);
398 EXPECT_NE(nullptr, session->state());
399 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 wp<RpcSession> weakSession = session;
402 session = nullptr;
403 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000404 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000405 }
406};
407
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000409// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410struct BinderRpcTestProcessSession {
411 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000412
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000413 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000414 sp<IBinder> rootBinder;
415
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000417 sp<IBinderRpcTest> rootIface;
418
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000419 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000420 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000421
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
423 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000424 EXPECT_NE(nullptr, rootIface);
425 if (rootIface == nullptr) return;
426
Steven Morelandaf4ca712021-05-24 23:22:08 +0000427 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000428 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000430 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000431 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000432 for (auto remoteCount : remoteCounts) {
433 EXPECT_EQ(remoteCount, 1);
434 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000435
Steven Moreland798e0d12021-07-14 23:19:25 +0000436 // even though it is on another thread, shutdown races with
437 // the transaction reply being written
438 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
439 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
440 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 }
442
443 rootIface = nullptr;
444 rootBinder = nullptr;
445 }
446};
447
Steven Morelandc1635952021-04-01 16:20:47 +0000448enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700449 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000450 UNIX,
451 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700452 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000453};
Yifan Hong702115c2021-06-24 15:39:18 -0700454static inline std::string PrintToString(SocketType socketType) {
455 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700456 case SocketType::PRECONNECTED:
457 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000458 case SocketType::UNIX:
459 return "unix_domain_socket";
460 case SocketType::VSOCK:
461 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700462 case SocketType::INET:
463 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000464 default:
465 LOG_ALWAYS_FATAL("Unknown socket type");
466 return "";
467 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000468}
Steven Morelandda573042021-06-12 01:13:45 +0000469
Yifan Hong1deca4b2021-09-10 16:16:44 -0700470static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700471 base::unique_fd serverFd(
472 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
473 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700474 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
475 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700476
477 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
478 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700479 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
480 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700481 }
482 return serverFd;
483}
484
Frederick Mayledc07cf82022-05-26 20:30:12 +0000485class BinderRpc
486 : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000487public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000488 struct Options {
489 size_t numThreads = 1;
490 size_t numSessions = 1;
491 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700492 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000493 };
494
Yifan Hong702115c2021-06-24 15:39:18 -0700495 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000496 auto [type, security, clientVersion, serverVersion] = info.param;
497 return PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
498 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Yifan Hong702115c2021-06-24 15:39:18 -0700499 }
500
Yifan Hong1deca4b2021-09-10 16:16:44 -0700501 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
502 uint64_t length = str.length();
503 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
504 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
505 }
506
507 static inline std::string readString(android::base::borrowed_fd fd) {
508 uint64_t length;
509 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
510 std::string ret(length, '\0');
511 CHECK(android::base::ReadFully(fd, ret.data(), length));
512 return ret;
513 }
514
515 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
516 Parcel parcel;
517 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
518 writeString(fd,
519 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
520 }
521
522 template <typename T>
523 static inline T readFromFd(android::base::borrowed_fd fd) {
524 std::string data = readString(fd);
525 Parcel parcel;
526 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
527 T object;
528 CHECK_EQ(OK, object.readFromParcel(&parcel));
529 return object;
530 }
531
Steven Morelandc1635952021-04-01 16:20:47 +0000532 // This creates a new process serving an interface on a certain number of
533 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000535 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
536 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000537
Yifan Hong702115c2021-06-24 15:39:18 -0700538 SocketType socketType = std::get<0>(GetParam());
539 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000540 uint32_t clientVersion = std::get<2>(GetParam());
541 uint32_t serverVersion = std::get<3>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000542
Steven Morelandda573042021-06-12 01:13:45 +0000543 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000544 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000545
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000547 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700548 android::base::borrowed_fd readEnd) {
549 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
550 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000551
Frederick Mayledc07cf82022-05-26 20:30:12 +0000552 server->setProtocolVersion(serverVersion);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000553 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000554
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000555 unsigned int outPort = 0;
556
Steven Morelandc1635952021-04-01 16:20:47 +0000557 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700558 case SocketType::PRECONNECTED:
559 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000560 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700561 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000562 break;
563 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700564 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000565 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700566 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700567 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700568 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700569 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700570 }
Steven Morelandc1635952021-04-01 16:20:47 +0000571 default:
572 LOG_ALWAYS_FATAL("Unknown socket type");
573 }
574
Yifan Hong1deca4b2021-09-10 16:16:44 -0700575 BinderRpcTestServerInfo serverInfo;
576 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700577 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700578 writeToFd(writeEnd, serverInfo);
579 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
580
581 if (rpcSecurity == RpcSecurity::TLS) {
582 for (const auto& clientCert : clientInfo.certs) {
583 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700584 certVerifier
585 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
586 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700587 }
588 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000589
Steven Moreland611d15f2021-05-01 01:28:27 +0000590 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000591
Steven Morelandf137de92021-04-24 01:54:26 +0000592 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000593
594 // Another thread calls shutdown. Wait for it to complete.
595 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000596 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000597 };
598
Yifan Hong1deca4b2021-09-10 16:16:44 -0700599 std::vector<sp<RpcSession>> sessions;
600 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
601 for (size_t i = 0; i < options.numSessions; i++) {
602 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
603 }
604
605 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
606 BinderRpcTestClientInfo clientInfo;
607 for (const auto& session : sessions) {
608 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700609 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700610 }
611 writeToFd(ret.host.writeEnd(), clientInfo);
612
613 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700614 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700615 CHECK_NE(0, serverInfo.port);
616 }
617
618 if (rpcSecurity == RpcSecurity::TLS) {
619 const auto& serverCert = serverInfo.cert.data;
620 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700621 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
622 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700623 }
624
Steven Moreland2372f9d2021-08-05 15:42:01 -0700625 status_t status;
626
Yifan Hong1deca4b2021-09-10 16:16:44 -0700627 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000628 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700629 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700630 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000631
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000632 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700633 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700634 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700635 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700636 });
Steven Moreland4198a122021-08-03 17:37:58 -0700637 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000638 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700639 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000640 break;
641 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700642 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000643 break;
644 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700645 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000646 break;
647 default:
648 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000649 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700650 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000651 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000652 }
Steven Morelandc1635952021-04-01 16:20:47 +0000653 return ret;
654 }
655
Steven Moreland4313d7e2021-07-15 23:41:22 +0000656 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000657 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700658 .proc = createRpcTestSocketServerProcess(
659 options,
660 [&](const sp<RpcServer>& server) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000661 server->setPerSessionRootObject([&](const void* addrPtr, size_t len) {
662 // UNIX sockets with abstract addresses return
663 // sizeof(sa_family_t)==2 in addrlen
664 CHECK_GE(len, sizeof(sa_family_t));
665 const sockaddr* addr = reinterpret_cast<const sockaddr*>(addrPtr);
Steven Moreland51c44a92021-10-14 16:50:35 -0700666 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
667 switch (addr->sa_family) {
668 case AF_UNIX:
669 // nothing to save
670 break;
671 case AF_VSOCK:
672 CHECK_EQ(len, sizeof(sockaddr_vm));
673 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
674 ->svm_port;
675 break;
676 case AF_INET:
677 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700678 service->port =
679 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
680 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700681 break;
682 case AF_INET6:
683 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700684 service->port =
685 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
686 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700687 break;
688 default:
689 LOG_ALWAYS_FATAL("Unrecognized address family %d",
690 addr->sa_family);
691 }
692 service->server = server;
693 return service;
694 });
695 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000696 };
697
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000698 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000699 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
700
701 return ret;
702 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700703
704 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
705 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000706};
707
Steven Morelandc1635952021-04-01 16:20:47 +0000708TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000709 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 ASSERT_NE(proc.rootBinder, nullptr);
711 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
712}
713
Steven Moreland4cf688f2021-03-31 01:48:58 +0000714TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000715 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000716 ASSERT_NE(proc.rootBinder, nullptr);
717 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
718}
719
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000721 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000722 for (auto session : proc.proc.sessions) {
723 ASSERT_NE(nullptr, session.root);
724 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000725 }
726}
727
Steven Moreland51c44a92021-10-14 16:50:35 -0700728TEST_P(BinderRpc, SeparateRootObject) {
729 SocketType type = std::get<0>(GetParam());
730 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
731 // we can't get port numbers for unix sockets
732 return;
733 }
734
735 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
736
737 int port1 = 0;
738 EXPECT_OK(proc.rootIface->getClientPort(&port1));
739
740 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
741 int port2;
742 EXPECT_OK(rootIface2->getClientPort(&port2));
743
744 // we should have a different IBinderRpcTest object created for each
745 // session, because we use setPerSessionRootObject
746 EXPECT_NE(port1, port2);
747}
748
Steven Morelandc1635952021-04-01 16:20:47 +0000749TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000750 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000751 Parcel data;
752 Parcel reply;
753 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
754}
755
Steven Moreland67753c32021-04-02 18:45:19 +0000756TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700757 auto proc1 = createRpcTestSocketServerProcess({});
758 auto proc2 = createRpcTestSocketServerProcess({});
759
760 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000761
762 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700763 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000764 p1.writeInt32(3);
765
Frederick Maylea4ed5672022-06-17 22:03:38 +0000766 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700767 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
768
Steven Moreland67753c32021-04-02 18:45:19 +0000769 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700770 p2.markForBinder(proc2.rootBinder);
771 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000772
773 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
774 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
775}
776
Steven Morelandc1635952021-04-01 16:20:47 +0000777TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000778 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000779 Parcel data;
780 data.markForBinder(proc.rootBinder);
781 Parcel reply;
782 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
783}
784
Steven Morelandc1635952021-04-01 16:20:47 +0000785TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000786 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000787 EXPECT_OK(proc.rootIface->sendString("asdf"));
788}
789
Steven Morelandc1635952021-04-01 16:20:47 +0000790TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000791 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000792 std::string doubled;
793 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
794 EXPECT_EQ("cool cool ", doubled);
795}
796
Steven Morelandc1635952021-04-01 16:20:47 +0000797TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000798 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000799 std::string single = std::string(1024, 'a');
800 std::string doubled;
801 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
802 EXPECT_EQ(single + single, doubled);
803}
804
Steven Morelandc1635952021-04-01 16:20:47 +0000805TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000806 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000807
808 int32_t pingResult;
809 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
810 EXPECT_EQ(OK, pingResult);
811
812 EXPECT_EQ(0, MyBinderRpcSession::gNum);
813}
814
Steven Morelandc1635952021-04-01 16:20:47 +0000815TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000816 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000817
818 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
819 sp<IBinder> outBinder;
820 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
821 EXPECT_EQ(inBinder, outBinder);
822
823 wp<IBinder> weak = inBinder;
824 inBinder = nullptr;
825 outBinder = nullptr;
826
827 // Force reading a reply, to process any pending dec refs from the other
828 // process (the other process will process dec refs there before processing
829 // the ping here).
830 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
831
832 EXPECT_EQ(nullptr, weak.promote());
833
834 EXPECT_EQ(0, MyBinderRpcSession::gNum);
835}
836
Steven Morelandc1635952021-04-01 16:20:47 +0000837TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000838 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000839
840 sp<IBinderRpcSession> session;
841 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
842
843 sp<IBinder> inBinder = IInterface::asBinder(session);
844 sp<IBinder> outBinder;
845 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
846 EXPECT_EQ(inBinder, outBinder);
847
848 wp<IBinder> weak = inBinder;
849 session = nullptr;
850 inBinder = nullptr;
851 outBinder = nullptr;
852
853 // Force reading a reply, to process any pending dec refs from the other
854 // process (the other process will process dec refs there before processing
855 // the ping here).
856 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
857
858 EXPECT_EQ(nullptr, weak.promote());
859}
860
Steven Morelandc1635952021-04-01 16:20:47 +0000861TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 sp<IBinder> outBinder;
865 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
866 EXPECT_EQ(nullptr, outBinder);
867}
868
Steven Morelandc1635952021-04-01 16:20:47 +0000869TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000870 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000871
872 IBinder* ptr = nullptr;
873 {
874 sp<IBinder> binder = new BBinder();
875 ptr = binder.get();
876 EXPECT_OK(proc.rootIface->holdBinder(binder));
877 }
878
879 sp<IBinder> held;
880 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
881
882 EXPECT_EQ(held.get(), ptr);
883
884 // stop holding binder, because we test to make sure references are cleaned
885 // up
886 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
887 // and flush ref counts
888 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
889}
890
891// START TESTS FOR LIMITATIONS OF SOCKET BINDER
892// These are behavioral differences form regular binder, where certain usecases
893// aren't supported.
894
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000895TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000896 auto proc1 = createRpcTestSocketServerProcess({});
897 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000898
899 sp<IBinder> outBinder;
900 EXPECT_EQ(INVALID_OPERATION,
901 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
902}
903
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000904TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000905 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000906
907 sp<IBinder> outBinder;
908 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000909 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000910 .transactionError());
911}
912
Steven Morelandc1635952021-04-01 16:20:47 +0000913TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000914 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000915
916 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
917 sp<IBinder> outBinder;
918 EXPECT_EQ(INVALID_OPERATION,
919 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
920}
921
Steven Morelandc1635952021-04-01 16:20:47 +0000922TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000923 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000924
925 // for historical reasons, IServiceManager interface only returns the
926 // exception code
927 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
928 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
929}
930
931// END TESTS FOR LIMITATIONS OF SOCKET BINDER
932
Steven Morelandc1635952021-04-01 16:20:47 +0000933TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000935
936 sp<IBinder> outBinder;
937 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
938 EXPECT_EQ(proc.rootBinder, outBinder);
939}
940
Steven Morelandc1635952021-04-01 16:20:47 +0000941TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000942 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000943
944 auto nastyNester = sp<MyBinderRpcTest>::make();
945 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
946
947 wp<IBinder> weak = nastyNester;
948 nastyNester = nullptr;
949 EXPECT_EQ(nullptr, weak.promote());
950}
951
Steven Morelandc1635952021-04-01 16:20:47 +0000952TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000953 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000954
955 sp<IBinder> a;
956 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
957
958 sp<IBinder> b;
959 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
960
961 EXPECT_EQ(a, b);
962}
963
Steven Morelandc1635952021-04-01 16:20:47 +0000964TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000965 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000966
967 sp<IBinder> a;
968 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
969 wp<IBinder> weak = a;
970 a = nullptr;
971
972 sp<IBinder> b;
973 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
974
975 // this is the wrong behavior, since BpBinder
976 // doesn't implement onIncStrongAttempted
977 // but make sure there is no crash
978 EXPECT_EQ(nullptr, weak.promote());
979
980 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
981
982 // In order to fix this:
983 // - need to have incStrongAttempted reflected across IPC boundary (wait for
984 // response to promote - round trip...)
985 // - sendOnLastWeakRef, to delete entries out of RpcState table
986 EXPECT_EQ(b, weak.promote());
987}
988
989#define expectSessions(expected, iface) \
990 do { \
991 int session; \
992 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
993 EXPECT_EQ(expected, session); \
994 } while (false)
995
Steven Morelandc1635952021-04-01 16:20:47 +0000996TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000997 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000998
999 sp<IBinderRpcSession> session;
1000 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
1001 std::string out;
1002 EXPECT_OK(session->getName(&out));
1003 EXPECT_EQ("aoeu", out);
1004
1005 expectSessions(1, proc.rootIface);
1006 session = nullptr;
1007 expectSessions(0, proc.rootIface);
1008}
1009
Steven Morelandc1635952021-04-01 16:20:47 +00001010TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001011 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001012
1013 std::vector<sp<IBinderRpcSession>> sessions;
1014
1015 for (size_t i = 0; i < 15; i++) {
1016 expectSessions(i, proc.rootIface);
1017 sp<IBinderRpcSession> session;
1018 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1019 sessions.push_back(session);
1020 }
1021 expectSessions(sessions.size(), proc.rootIface);
1022 for (size_t i = 0; i < sessions.size(); i++) {
1023 std::string out;
1024 EXPECT_OK(sessions.at(i)->getName(&out));
1025 EXPECT_EQ(std::to_string(i), out);
1026 }
1027 expectSessions(sessions.size(), proc.rootIface);
1028
1029 while (!sessions.empty()) {
1030 sessions.pop_back();
1031 expectSessions(sessions.size(), proc.rootIface);
1032 }
1033 expectSessions(0, proc.rootIface);
1034}
1035
1036size_t epochMillis() {
1037 using std::chrono::duration_cast;
1038 using std::chrono::milliseconds;
1039 using std::chrono::seconds;
1040 using std::chrono::system_clock;
1041 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1042}
1043
Steven Morelandc1635952021-04-01 16:20:47 +00001044TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001045 constexpr size_t kNumThreads = 10;
1046
Steven Moreland4313d7e2021-07-15 23:41:22 +00001047 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001048
1049 EXPECT_OK(proc.rootIface->lock());
1050
1051 // block all but one thread taking locks
1052 std::vector<std::thread> ts;
1053 for (size_t i = 0; i < kNumThreads - 1; i++) {
1054 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1055 }
1056
1057 usleep(100000); // give chance for calls on other threads
1058
1059 // other calls still work
1060 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1061
1062 constexpr size_t blockTimeMs = 500;
1063 size_t epochMsBefore = epochMillis();
1064 // after this, we should never see a response within this time
1065 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1066
1067 // this call should be blocked for blockTimeMs
1068 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1069
1070 size_t epochMsAfter = epochMillis();
1071 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1072
1073 for (auto& t : ts) t.join();
1074}
1075
Yifan Hong1f44f982021-10-08 17:16:47 -07001076void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1077 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001078 size_t epochMsBefore = epochMillis();
1079
1080 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001081 for (size_t i = 0; i < numCalls; i++) {
1082 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001083 }
1084
1085 for (auto& t : ts) t.join();
1086
1087 size_t epochMsAfter = epochMillis();
1088
Yifan Hong1f44f982021-10-08 17:16:47 -07001089 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001090
1091 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001092 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1093}
1094
1095TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1096 constexpr size_t kNumThreads = 10;
1097 constexpr size_t kNumCalls = kNumThreads + 3;
1098 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1099 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1100}
1101
1102TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1103 constexpr size_t kNumThreads = 20;
1104 constexpr size_t kNumOutgoingConnections = 10;
1105 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1106 auto proc = createRpcTestSocketServerProcess(
1107 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1108 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001109}
1110
Steven Morelandc1635952021-04-01 16:20:47 +00001111TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001112 constexpr size_t kNumClientThreads = 10;
1113 constexpr size_t kNumServerThreads = 10;
1114 constexpr size_t kNumCalls = 100;
1115
Steven Moreland4313d7e2021-07-15 23:41:22 +00001116 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001117
1118 std::vector<std::thread> threads;
1119 for (size_t i = 0; i < kNumClientThreads; i++) {
1120 threads.push_back(std::thread([&] {
1121 for (size_t j = 0; j < kNumCalls; j++) {
1122 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001123 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001124 EXPECT_EQ(proc.rootBinder, out);
1125 }
1126 }));
1127 }
1128
1129 for (auto& t : threads) t.join();
1130}
1131
Steven Moreland925ba0a2021-09-17 18:06:32 -07001132static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1133 std::vector<std::thread> threads;
1134 for (size_t i = 0; i < threadCount; i++) {
1135 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1136 }
1137 for (auto& t : threads) t.join();
1138}
1139
Steven Morelandc6046982021-04-20 00:49:42 +00001140TEST_P(BinderRpc, OnewayStressTest) {
1141 constexpr size_t kNumClientThreads = 10;
1142 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001143 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001144
Steven Moreland4313d7e2021-07-15 23:41:22 +00001145 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001146
1147 std::vector<std::thread> threads;
1148 for (size_t i = 0; i < kNumClientThreads; i++) {
1149 threads.push_back(std::thread([&] {
1150 for (size_t j = 0; j < kNumCalls; j++) {
1151 EXPECT_OK(proc.rootIface->sendString("a"));
1152 }
Steven Morelandc6046982021-04-20 00:49:42 +00001153 }));
1154 }
1155
1156 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001157
1158 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001159}
1160
Steven Morelandc1635952021-04-01 16:20:47 +00001161TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001162 constexpr size_t kReallyLongTimeMs = 100;
1163 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1164
Steven Moreland4313d7e2021-07-15 23:41:22 +00001165 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001166
1167 size_t epochMsBefore = epochMillis();
1168
1169 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1170
1171 size_t epochMsAfter = epochMillis();
1172 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1173}
1174
Steven Morelandc1635952021-04-01 16:20:47 +00001175TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001176 constexpr size_t kNumSleeps = 10;
1177 constexpr size_t kNumExtraServerThreads = 4;
1178 constexpr size_t kSleepMs = 50;
1179
1180 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001181 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001182
1183 EXPECT_OK(proc.rootIface->lock());
1184
Steven Moreland1c678802021-09-17 16:48:47 -07001185 size_t epochMsBefore = epochMillis();
1186
1187 // all these *Async commands should be queued on the server sequentially,
1188 // even though there are multiple threads.
1189 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001190 proc.rootIface->sleepMsAsync(kSleepMs);
1191 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001192 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1193
Steven Moreland1c678802021-09-17 16:48:47 -07001194 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001195 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001196
Steven Moreland5553ac42020-11-11 02:14:45 +00001197 size_t epochMsAfter = epochMillis();
1198
1199 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001200
Steven Moreland925ba0a2021-09-17 18:06:32 -07001201 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001202}
1203
Steven Morelandd45be622021-06-04 02:19:37 +00001204TEST_P(BinderRpc, OnewayCallExhaustion) {
1205 constexpr size_t kNumClients = 2;
1206 constexpr size_t kTooLongMs = 1000;
1207
Steven Moreland4313d7e2021-07-15 23:41:22 +00001208 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001209
1210 // Build up oneway calls on the second session to make sure it terminates
1211 // and shuts down. The first session should be unaffected (proc destructor
1212 // checks the first session).
1213 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1214
1215 std::vector<std::thread> threads;
1216 for (size_t i = 0; i < kNumClients; i++) {
1217 // one of these threads will get stuck queueing a transaction once the
1218 // socket fills up, the other will be able to fill up transactions on
1219 // this object
1220 threads.push_back(std::thread([&] {
1221 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1222 }
1223 }));
1224 }
1225 for (auto& t : threads) t.join();
1226
1227 Status status = iface->sleepMsAsync(kTooLongMs);
1228 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1229
Steven Moreland798e0d12021-07-14 23:19:25 +00001230 // now that it has died, wait for the remote session to shutdown
1231 std::vector<int32_t> remoteCounts;
1232 do {
1233 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1234 } while (remoteCounts.size() == kNumClients);
1235
Steven Morelandd45be622021-06-04 02:19:37 +00001236 // the second session should be shutdown in the other process by the time we
1237 // are able to join above (it'll only be hung up once it finishes processing
1238 // any pending commands). We need to erase this session from the record
1239 // here, so that the destructor for our session won't check that this
1240 // session is valid, but we still want it to test the other session.
1241 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1242}
1243
Steven Moreland659416d2021-05-11 00:47:50 +00001244TEST_P(BinderRpc, Callbacks) {
1245 const static std::string kTestString = "good afternoon!";
1246
Steven Morelandc7d40132021-06-10 03:42:11 +00001247 for (bool callIsOneway : {true, false}) {
1248 for (bool callbackIsOneway : {true, false}) {
1249 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001250 auto proc = createRpcTestSocketServerProcess(
1251 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001252 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001253
Steven Morelandc7d40132021-06-10 03:42:11 +00001254 if (callIsOneway) {
1255 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1256 kTestString));
1257 } else {
1258 EXPECT_OK(
1259 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1260 }
Steven Moreland659416d2021-05-11 00:47:50 +00001261
Steven Moreland03ecce62022-05-13 23:22:05 +00001262 // if both transactions are synchronous and the response is sent back on the
1263 // same thread, everything should have happened in a nested call. Otherwise,
1264 // the callback will be processed on another thread.
1265 if (callIsOneway || callbackIsOneway || delayed) {
1266 using std::literals::chrono_literals::operator""s;
1267 std::unique_lock<std::mutex> _l(cb->mMutex);
1268 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1269 }
Steven Moreland659416d2021-05-11 00:47:50 +00001270
Steven Morelandc7d40132021-06-10 03:42:11 +00001271 EXPECT_EQ(cb->mValues.size(), 1)
1272 << "callIsOneway: " << callIsOneway
1273 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1274 if (cb->mValues.empty()) continue;
1275 EXPECT_EQ(cb->mValues.at(0), kTestString)
1276 << "callIsOneway: " << callIsOneway
1277 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001278
Steven Morelandc7d40132021-06-10 03:42:11 +00001279 // since we are severing the connection, we need to go ahead and
1280 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001281 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1282 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1283 }
Steven Moreland659416d2021-05-11 00:47:50 +00001284
Steven Moreland1b304292021-07-15 22:59:34 +00001285 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001286 // need to manually shut it down
1287 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001288
Steven Morelandc7d40132021-06-10 03:42:11 +00001289 proc.expectAlreadyShutdown = true;
1290 }
Steven Moreland659416d2021-05-11 00:47:50 +00001291 }
1292 }
1293}
1294
Steven Moreland195edb82021-06-08 02:44:39 +00001295TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001296 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001297 auto cb = sp<MyBinderRpcCallback>::make();
1298
1299 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1300 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1301}
1302
Steven Morelandc1635952021-04-01 16:20:47 +00001303TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001304 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001305 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001306
1307 // make sure there is some state during crash
1308 // 1. we hold their binder
1309 sp<IBinderRpcSession> session;
1310 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1311 // 2. they hold our binder
1312 sp<IBinder> binder = new BBinder();
1313 EXPECT_OK(proc.rootIface->holdBinder(binder));
1314
1315 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1316 << "Do death cleanup: " << doDeathCleanup;
1317
Steven Morelandaf4ca712021-05-24 23:22:08 +00001318 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001319 }
1320}
1321
Steven Morelandd7302072021-05-15 01:32:04 +00001322TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Morelanda83191d2021-10-27 10:14:53 -07001323 bool okToFork = ProcessState::selfOrNull() == nullptr;
1324
Steven Moreland4313d7e2021-07-15 23:41:22 +00001325 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001326
Steven Morelanda83191d2021-10-27 10:14:53 -07001327 // If this process has used ProcessState already, then the forked process
1328 // cannot use it at all. If this process hasn't used it (depending on the
1329 // order tests are run), then the forked process can use it, and we'll only
1330 // catch the invalid usage the second time. Such is the burden of global
1331 // state!
1332 if (okToFork) {
1333 // we can't allocate IPCThreadState so actually the first time should
1334 // succeed :(
1335 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1336 }
Steven Morelandd7302072021-05-15 01:32:04 +00001337
1338 // second time! we catch the error :)
1339 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1340
Steven Morelandaf4ca712021-05-24 23:22:08 +00001341 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001342}
1343
Steven Moreland37aff182021-03-26 02:04:16 +00001344TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001345 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001346
1347 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1348 ASSERT_NE(binder, nullptr);
1349
1350 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1351}
1352
1353TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001354 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001355
1356 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1357 ASSERT_NE(binder, nullptr);
1358
1359 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1360 ASSERT_NE(ndkBinder, nullptr);
1361
1362 std::string out;
1363 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1364 ASSERT_TRUE(status.isOk()) << status.getDescription();
1365 ASSERT_EQ("aoeuaoeu", out);
1366}
1367
Steven Moreland5553ac42020-11-11 02:14:45 +00001368ssize_t countFds() {
1369 DIR* dir = opendir("/proc/self/fd/");
1370 if (dir == nullptr) return -1;
1371 ssize_t ret = 0;
1372 dirent* ent;
1373 while ((ent = readdir(dir)) != nullptr) ret++;
1374 closedir(dir);
1375 return ret;
1376}
1377
Steven Morelandc1635952021-04-01 16:20:47 +00001378TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001379 ssize_t beforeFds = countFds();
1380 ASSERT_GE(beforeFds, 0);
1381 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001382 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001383 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1384 }
1385 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1386}
1387
Devin Moore800b2252021-10-15 16:22:57 +00001388TEST_P(BinderRpc, AidlDelegatorTest) {
1389 auto proc = createRpcTestSocketServerProcess({});
1390 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1391 ASSERT_NE(nullptr, myDelegator);
1392
1393 std::string doubled;
1394 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1395 EXPECT_EQ("cool cool ", doubled);
1396}
1397
Steven Morelandda573042021-06-12 01:13:45 +00001398static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001399 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001400 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001401 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001402 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1403 if (status == -EAFNOSUPPORT) {
1404 return false;
1405 }
1406 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1407 }
Steven Morelandda573042021-06-12 01:13:45 +00001408 server->start();
1409
Yifan Hongfdd9f692021-09-09 15:12:52 -07001410 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001411 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001412 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001413 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1414 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001415}
1416
Yifan Hong1deca4b2021-09-10 16:16:44 -07001417static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1418 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1419
1420 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001421
1422 static bool hasVsockLoopback = testSupportVsockLoopback();
1423
1424 if (hasVsockLoopback) {
1425 ret.push_back(SocketType::VSOCK);
1426 }
1427
1428 return ret;
1429}
1430
Frederick Mayledc07cf82022-05-26 20:30:12 +00001431static std::vector<uint32_t> testVersions() {
1432 std::vector<uint32_t> versions;
1433 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1434 versions.push_back(i);
1435 }
1436 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1437 return versions;
1438}
1439
Yifan Hong702115c2021-06-24 15:39:18 -07001440INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1441 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001442 ::testing::ValuesIn(RpcSecurityValues()),
1443 ::testing::ValuesIn(testVersions()),
1444 ::testing::ValuesIn(testVersions())),
Yifan Hong702115c2021-06-24 15:39:18 -07001445 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001446
Yifan Hong702115c2021-06-24 15:39:18 -07001447class BinderRpcServerRootObject
1448 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001449
1450TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1451 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1452 auto setRootObject = [](bool isStrong) -> SetFn {
1453 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1454 };
1455
Yifan Hong702115c2021-06-24 15:39:18 -07001456 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1457 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001458 auto binder1 = sp<BBinder>::make();
1459 IBinder* binderRaw1 = binder1.get();
1460 setRootObject(isStrong1)(server.get(), binder1);
1461 EXPECT_EQ(binderRaw1, server->getRootObject());
1462 binder1.clear();
1463 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1464
1465 auto binder2 = sp<BBinder>::make();
1466 IBinder* binderRaw2 = binder2.get();
1467 setRootObject(isStrong2)(server.get(), binder2);
1468 EXPECT_EQ(binderRaw2, server->getRootObject());
1469 binder2.clear();
1470 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1471}
1472
1473INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001474 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1475 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001476
Yifan Hong1a235852021-05-13 16:07:47 -07001477class OneOffSignal {
1478public:
1479 // If notify() was previously called, or is called within |duration|, return true; else false.
1480 template <typename R, typename P>
1481 bool wait(std::chrono::duration<R, P> duration) {
1482 std::unique_lock<std::mutex> lock(mMutex);
1483 return mCv.wait_for(lock, duration, [this] { return mValue; });
1484 }
1485 void notify() {
1486 std::unique_lock<std::mutex> lock(mMutex);
1487 mValue = true;
1488 lock.unlock();
1489 mCv.notify_all();
1490 }
1491
1492private:
1493 std::mutex mMutex;
1494 std::condition_variable mCv;
1495 bool mValue = false;
1496};
1497
Frederick Mayledc07cf82022-05-26 20:30:12 +00001498TEST_P(BinderRpcServerOnly, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001499 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001500 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1501 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001502 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001503 auto joinEnds = std::make_shared<OneOffSignal>();
1504
1505 // If things are broken and the thread never stops, don't block other tests. Because the thread
1506 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1507 // shared pointers are passed.
1508 std::thread([server, joinEnds] {
1509 server->join();
1510 joinEnds->notify();
1511 }).detach();
1512
1513 bool shutdown = false;
1514 for (int i = 0; i < 10 && !shutdown; i++) {
1515 usleep(300 * 1000); // 300ms; total 3s
1516 if (server->shutdown()) shutdown = true;
1517 }
1518 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1519
1520 ASSERT_TRUE(joinEnds->wait(2s))
1521 << "After server->shutdown() returns true, join() did not stop after 2s";
1522}
1523
Yifan Hong194acf22021-06-29 18:44:56 -07001524TEST(BinderRpc, Java) {
1525#if !defined(__ANDROID__)
1526 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1527 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1528 "to binderHostDeviceTest. Hence, just disable this test on host.";
1529#endif // !__ANDROID__
1530 sp<IServiceManager> sm = defaultServiceManager();
1531 ASSERT_NE(nullptr, sm);
1532 // Any Java service with non-empty getInterfaceDescriptor() would do.
1533 // Let's pick batteryproperties.
1534 auto binder = sm->checkService(String16("batteryproperties"));
1535 ASSERT_NE(nullptr, binder);
1536 auto descriptor = binder->getInterfaceDescriptor();
1537 ASSERT_GE(descriptor.size(), 0);
1538 ASSERT_EQ(OK, binder->pingBinder());
1539
1540 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001541 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001542 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001543 auto socket = rpcServer->releaseServer();
1544
1545 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001546 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1547
Yifan Honge3caaf22022-01-12 14:46:56 -08001548 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1549 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001550 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001551 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1552 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001553 << statusToString(setRpcClientDebugStatus);
1554 GTEST_SKIP();
1555 }
1556
1557 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001558
1559 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001560 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001561 auto rpcBinder = rpcSession->getRootObject();
1562 ASSERT_NE(nullptr, rpcBinder);
1563
1564 ASSERT_EQ(OK, rpcBinder->pingBinder());
1565
1566 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1567 << "getInterfaceDescriptor should not crash system_server";
1568 ASSERT_EQ(OK, rpcBinder->pingBinder());
1569}
1570
Frederick Mayledc07cf82022-05-26 20:30:12 +00001571INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1572 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1573 ::testing::ValuesIn(testVersions())),
1574 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001575
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001576class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001577public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001578 // Only parameterized only server version because `RpcSession` is bypassed
1579 // in the client half of the tests.
1580 using Param =
1581 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001582 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001583
1584 // A server that handles client socket connections.
1585 class Server {
1586 public:
1587 explicit Server() {}
1588 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001589 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001590 [[nodiscard]] AssertionResult setUp(
1591 const Param& param,
1592 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001593 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001594 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001595 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001596 switch (socketType) {
1597 case SocketType::PRECONNECTED: {
1598 return AssertionFailure() << "Not supported by this test";
1599 } break;
1600 case SocketType::UNIX: {
1601 auto addr = allocateSocketAddress();
1602 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1603 if (status != OK) {
1604 return AssertionFailure()
1605 << "setupUnixDomainServer: " << statusToString(status);
1606 }
1607 mConnectToServer = [addr] {
1608 return connectTo(UnixSocketAddress(addr.c_str()));
1609 };
1610 } break;
1611 case SocketType::VSOCK: {
1612 auto port = allocateVsockPort();
1613 auto status = rpcServer->setupVsockServer(port);
1614 if (status != OK) {
1615 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1616 }
1617 mConnectToServer = [port] {
1618 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1619 };
1620 } break;
1621 case SocketType::INET: {
1622 unsigned int port;
1623 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1624 if (status != OK) {
1625 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1626 }
1627 mConnectToServer = [port] {
1628 const char* addr = kLocalInetAddress;
1629 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1630 if (aiStart == nullptr) return base::unique_fd{};
1631 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1632 auto fd = connectTo(
1633 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1634 if (fd.ok()) return fd;
1635 }
1636 ALOGE("None of the socket address resolved for %s:%u can be connected",
1637 addr, port);
1638 return base::unique_fd{};
1639 };
1640 }
1641 }
1642 mFd = rpcServer->releaseServer();
1643 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001644 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001645 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1646 mSetup = true;
1647 return AssertionSuccess();
1648 }
1649 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1650 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1651 return mCertVerifier;
1652 }
1653 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1654 void start() {
1655 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1656 mThread = std::make_unique<std::thread>(&Server::run, this);
1657 }
1658 void run() {
1659 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1660
1661 std::vector<std::thread> threads;
1662 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1663 base::unique_fd acceptedFd(
1664 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1665 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1666 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1667 }
1668
1669 for (auto& thread : threads) thread.join();
1670 }
1671 void handleOne(android::base::unique_fd acceptedFd) {
1672 ASSERT_TRUE(acceptedFd.ok());
1673 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1674 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001675 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001676 }
Yifan Honge07d2732021-09-13 21:59:14 -07001677 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001678 shutdown();
1679 join();
1680 }
1681 void shutdown() { mFdTrigger->trigger(); }
1682
1683 void setPostConnect(
1684 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1685 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001686 }
1687
1688 private:
1689 std::unique_ptr<std::thread> mThread;
1690 ConnectToServer mConnectToServer;
1691 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1692 base::unique_fd mFd;
1693 std::unique_ptr<RpcTransportCtx> mCtx;
1694 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1695 std::make_shared<RpcCertificateVerifierSimple>();
1696 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001697 // The function invoked after connection and handshake. By default, it is
1698 // |defaultPostConnect| that sends |kMessage| to the client.
1699 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1700 Server::defaultPostConnect;
1701
1702 void join() {
1703 if (mThread != nullptr) {
1704 mThread->join();
1705 mThread = nullptr;
1706 }
1707 }
1708
1709 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1710 FdTrigger* fdTrigger) {
1711 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001712 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001713 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1714 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001715 if (status != OK) return AssertionFailure() << statusToString(status);
1716 return AssertionSuccess();
1717 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718 };
1719
1720 class Client {
1721 public:
1722 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1723 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001724 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001725 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1726 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 mFdTrigger = FdTrigger::make();
1728 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1729 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1730 return AssertionSuccess();
1731 }
1732 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1733 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1734 return mCertVerifier;
1735 }
Yifan Hong67519322021-09-13 18:51:16 -07001736 // connect() and do handshake
1737 bool setUpTransport() {
1738 mFd = mConnectToServer();
1739 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1740 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1741 return mClientTransport != nullptr;
1742 }
1743 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1744 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1745 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001746 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001747 status_t readStatus =
1748 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
1749 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001750 if (readStatus != OK) {
1751 return AssertionFailure() << statusToString(readStatus);
1752 }
1753 if (readMessage != expectedMessage) {
1754 return AssertionFailure()
1755 << "Expected " << expectedMessage << ", actual " << readMessage;
1756 }
1757 return AssertionSuccess();
1758 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001759 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001760 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001761 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1762 return;
1763 }
1764 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001765 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001766 }
1767
1768 private:
1769 ConnectToServer mConnectToServer;
1770 base::unique_fd mFd;
1771 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1772 std::unique_ptr<RpcTransportCtx> mCtx;
1773 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1774 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001775 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001776 };
1777
1778 // Make A trust B.
1779 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001780 static status_t trust(RpcSecurity rpcSecurity,
1781 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1782 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001784 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1785 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1786 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787 }
1788
1789 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790};
1791
1792class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1793public:
1794 using Server = RpcTransportTestUtils::Server;
1795 using Client = RpcTransportTestUtils::Client;
1796 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001797 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001798 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1799 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001800 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001801 return ret;
1802 }
1803 static std::vector<ParamType> getRpcTranportTestParams() {
1804 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001805 for (auto serverVersion : testVersions()) {
1806 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1807 for (auto rpcSecurity : RpcSecurityValues()) {
1808 switch (rpcSecurity) {
1809 case RpcSecurity::RAW: {
1810 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1811 } break;
1812 case RpcSecurity::TLS: {
1813 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1814 serverVersion);
1815 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1816 serverVersion);
1817 } break;
1818 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001819 }
1820 }
1821 }
1822 return ret;
1823 }
1824 template <typename A, typename B>
1825 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001826 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1827 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001828 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1829 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001830};
1831
1832TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001833 auto server = std::make_unique<Server>();
1834 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001835
1836 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001837 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001838
1839 ASSERT_EQ(OK, trust(&client, server));
1840 ASSERT_EQ(OK, trust(server, &client));
1841
1842 server->start();
1843 client.run();
1844}
1845
1846TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001847 auto server = std::make_unique<Server>();
1848 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001849
1850 std::vector<Client> clients;
1851 for (int i = 0; i < 2; i++) {
1852 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001853 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001854 ASSERT_EQ(OK, trust(&client, server));
1855 ASSERT_EQ(OK, trust(server, &client));
1856 }
1857
1858 server->start();
1859 for (auto& client : clients) client.run();
1860}
1861
1862TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001863 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1864 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001865
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001866 auto untrustedServer = std::make_unique<Server>();
1867 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001868
1869 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001870 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871
1872 ASSERT_EQ(OK, trust(untrustedServer, &client));
1873
1874 untrustedServer->start();
1875
1876 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1877 // the client can't verify the server's identity.
1878 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1879 client.run(handshakeOk);
1880}
1881TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001882 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1883 (void)serverVersion;
1884
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001885 auto validServer = std::make_unique<Server>();
1886 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001887
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001888 auto maliciousServer = std::make_unique<Server>();
1889 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001890
1891 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001892 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001893
1894 ASSERT_EQ(OK, trust(&client, validServer));
1895 ASSERT_EQ(OK, trust(validServer, &client));
1896 ASSERT_EQ(OK, trust(maliciousServer, &client));
1897
1898 maliciousServer->start();
1899
1900 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1901 // the client can't verify the server's identity.
1902 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1903 client.run(handshakeOk);
1904}
1905
1906TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001907 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1908 (void)serverVersion;
1909
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001910 auto server = std::make_unique<Server>();
1911 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001912
1913 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001914 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001915
1916 ASSERT_EQ(OK, trust(&client, server));
1917
1918 server->start();
1919
1920 // For TLS, Client should be able to verify server's identity, so client should see
1921 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1922 // identity and should drop the connection, so client shouldn't be able to read anything.
1923 bool readOk = rpcSecurity != RpcSecurity::TLS;
1924 client.run(true, readOk);
1925}
1926
1927TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001928 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1929 (void)serverVersion;
1930
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931 auto server = std::make_unique<Server>();
1932 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001933
1934 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001935 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001936 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001938
1939 ASSERT_EQ(OK, trust(&validClient, server));
1940 ASSERT_EQ(OK, trust(&maliciousClient, server));
1941
1942 server->start();
1943
1944 // See UntrustedClient.
1945 bool readOk = rpcSecurity != RpcSecurity::TLS;
1946 maliciousClient.run(true, readOk);
1947}
1948
Yifan Hong67519322021-09-13 18:51:16 -07001949TEST_P(RpcTransportTest, Trigger) {
1950 std::string msg2 = ", world!";
1951 std::mutex writeMutex;
1952 std::condition_variable writeCv;
1953 bool shouldContinueWriting = false;
1954 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001955 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001956 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001957 auto status =
1958 serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001959 if (status != OK) return AssertionFailure() << statusToString(status);
1960
1961 {
1962 std::unique_lock<std::mutex> lock(writeMutex);
1963 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1964 return AssertionFailure() << "write barrier not cleared in time!";
1965 }
1966 }
1967
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001968 iovec msg2Iov{msg2.data(), msg2.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001969 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt);
Steven Morelandc591b472021-09-16 13:56:11 -07001970 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001971 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001972 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001973 << statusToString(status);
1974 return AssertionSuccess();
1975 };
1976
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001977 auto server = std::make_unique<Server>();
1978 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001979
1980 // Set up client
1981 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001982 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001983
1984 // Exchange keys
1985 ASSERT_EQ(OK, trust(&client, server));
1986 ASSERT_EQ(OK, trust(server, &client));
1987
1988 server->setPostConnect(serverPostConnect);
1989
Yifan Hong67519322021-09-13 18:51:16 -07001990 server->start();
1991 // connect() to server and do handshake
1992 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001993 // read the first message. This ensures that server has finished handshake and start handling
1994 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001995 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001996 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1997 // write is on an FdTrigger that has been shut down.
1998 server->shutdown();
1999 // Continues server thread to write the second message.
2000 {
Yifan Hong22211f82021-09-14 12:32:25 -07002001 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002002 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002003 }
Yifan Hong22211f82021-09-14 12:32:25 -07002004 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002005 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002006 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002007 // On the client side, second read fails with DEAD_OBJECT
2008 ASSERT_FALSE(client.readMessage(msg2));
2009}
2010
Yifan Hong1deca4b2021-09-10 16:16:44 -07002011INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002012 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002013 RpcTransportTest::PrintParamInfo);
2014
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002015class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002016 : public testing::TestWithParam<
2017 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002018public:
2019 template <typename A, typename B>
2020 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002021 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2022 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2024 }
2025 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002026 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2027 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2028 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002029 };
2030};
2031
2032TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002033 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002034
2035 std::vector<uint8_t> pkeyData, certData;
2036 {
2037 auto pkey = makeKeyPairForSelfSignedCert();
2038 ASSERT_NE(nullptr, pkey);
2039 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2040 ASSERT_NE(nullptr, cert);
2041 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2042 certData = serializeCertificate(cert.get(), certificateFormat);
2043 }
2044
2045 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2046 auto desCert = deserializeCertificate(certData, certificateFormat);
2047 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002048 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2049 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002050
2051 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2052 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2053
2054 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2055 ASSERT_TRUE(client.setUp(utilsParam));
2056
2057 ASSERT_EQ(OK, trust(&client, server));
2058 ASSERT_EQ(OK, trust(server, &client));
2059
2060 server->start();
2061 client.run();
2062}
2063
2064INSTANTIATE_TEST_CASE_P(
2065 BinderRpc, RpcTransportTlsKeyTest,
2066 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2067 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002068 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2069 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002070 RpcTransportTlsKeyTest::PrintParamInfo);
2071
Steven Morelandc1635952021-04-01 16:20:47 +00002072} // namespace android
2073
2074int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002075 ::testing::InitGoogleTest(&argc, argv);
2076 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002077
Steven Moreland5553ac42020-11-11 02:14:45 +00002078 return RUN_ALL_TESTS();
2079}