blob: 141fa38114dd5c359aaefeb5b528d8fab1a35b5a [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 }
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000205 Status getNullBinder(sp<IBinder>* out) override {
206 out->clear();
207 return Status::ok();
208 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000209 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
210 if (binder == nullptr) {
211 std::cout << "Received null binder!" << std::endl;
212 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
213 }
214 *out = binder->pingBinder();
215 return Status::ok();
216 }
217 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
218 *out = binder;
219 return Status::ok();
220 }
221 static sp<IBinder> mHeldBinder;
222 Status holdBinder(const sp<IBinder>& binder) override {
223 mHeldBinder = binder;
224 return Status::ok();
225 }
226 Status getHeldBinder(sp<IBinder>* held) override {
227 *held = mHeldBinder;
228 return Status::ok();
229 }
230 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
231 if (count <= 0) return Status::ok();
232 return binder->nestMe(this, count - 1);
233 }
234 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
235 static sp<IBinder> binder = new BBinder;
236 *out = binder;
237 return Status::ok();
238 }
239 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
240 *out = new MyBinderRpcSession(name);
241 return Status::ok();
242 }
243 Status getNumOpenSessions(int32_t* out) override {
244 *out = MyBinderRpcSession::gNum;
245 return Status::ok();
246 }
247
248 std::mutex blockMutex;
249 Status lock() override {
250 blockMutex.lock();
251 return Status::ok();
252 }
253 Status unlockInMsAsync(int32_t ms) override {
254 usleep(ms * 1000);
255 blockMutex.unlock();
256 return Status::ok();
257 }
258 Status lockUnlock() override {
259 std::lock_guard<std::mutex> _l(blockMutex);
260 return Status::ok();
261 }
262
263 Status sleepMs(int32_t ms) override {
264 usleep(ms * 1000);
265 return Status::ok();
266 }
267
268 Status sleepMsAsync(int32_t ms) override {
269 // In-process binder calls are asynchronous, but the call to this method
270 // is synchronous wrt its client. This in/out-process threading model
271 // diffentiation is a classic binder leaky abstraction (for better or
272 // worse) and is preserved here the way binder sockets plugs itself
273 // into BpBinder, as nothing is changed at the higher levels
274 // (IInterface) which result in this behavior.
275 return sleepMs(ms);
276 }
277
Steven Moreland659416d2021-05-11 00:47:50 +0000278 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
279 const std::string& value) override {
280 if (callback == nullptr) {
281 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
282 }
283
284 if (delayed) {
285 std::thread([=]() {
286 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000287 Status status = doCallback(callback, oneway, false, value);
288 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000289 }).detach();
290 return Status::ok();
291 }
292
293 if (oneway) {
294 return callback->sendOnewayCallback(value);
295 }
296
297 return callback->sendCallback(value);
298 }
299
Steven Morelandc7d40132021-06-10 03:42:11 +0000300 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
301 const std::string& value) override {
302 return doCallback(callback, oneway, delayed, value);
303 }
304
Steven Moreland5553ac42020-11-11 02:14:45 +0000305 Status die(bool cleanup) override {
306 if (cleanup) {
307 exit(1);
308 } else {
309 _exit(1);
310 }
311 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000312
313 Status scheduleShutdown() override {
314 sp<RpcServer> strongServer = server.promote();
315 if (strongServer == nullptr) {
316 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
317 }
318 std::thread([=] {
319 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
320 }).detach();
321 return Status::ok();
322 }
323
Steven Morelandd7302072021-05-15 01:32:04 +0000324 Status useKernelBinderCallingId() override {
325 // this is WRONG! It does not make sense when using RPC binder, and
326 // because it is SO wrong, and so much code calls this, it should abort!
327
328 (void)IPCThreadState::self()->getCallingPid();
329 return Status::ok();
330 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000331};
332sp<IBinder> MyBinderRpcTest::mHeldBinder;
333
334class Process {
335public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700336 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700337 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
338 android::base::borrowed_fd /* readEnd */)>& f) {
339 android::base::unique_fd childWriteEnd;
340 android::base::unique_fd childReadEnd;
341 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
342 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000343 if (0 == (mPid = fork())) {
344 // racey: assume parent doesn't crash before this is set
345 prctl(PR_SET_PDEATHSIG, SIGHUP);
346
Yifan Hong1deca4b2021-09-10 16:16:44 -0700347 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000348
349 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000350 }
351 }
352 ~Process() {
353 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000354 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000355 }
356 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700357 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000359
360private:
361 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700362 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700363 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000364};
365
366static std::string allocateSocketAddress() {
367 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000368 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700369 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
370 unlink(ret.c_str());
371 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000372};
373
Steven Morelandda573042021-06-12 01:13:45 +0000374static unsigned int allocateVsockPort() {
375 static unsigned int vsockPort = 3456;
376 return vsockPort++;
377}
378
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000380 // reference to process hosting a socket server
381 Process host;
382
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000383 struct SessionInfo {
384 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000385 sp<IBinder> root;
386 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000387
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000388 // client session objects associated with other process
389 // each one represents a separate session
390 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000391
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 ProcessSession(ProcessSession&&) = default;
393 ~ProcessSession() {
394 for (auto& session : sessions) {
395 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000396 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000397
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 for (auto& info : sessions) {
399 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 EXPECT_NE(nullptr, session);
402 EXPECT_NE(nullptr, session->state());
403 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000404
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 wp<RpcSession> weakSession = session;
406 session = nullptr;
407 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000408 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000409 }
410};
411
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000413// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000414struct BinderRpcTestProcessSession {
415 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000416
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000418 sp<IBinder> rootBinder;
419
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 sp<IBinderRpcTest> rootIface;
422
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000423 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000424 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000425
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000426 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
427 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000428 EXPECT_NE(nullptr, rootIface);
429 if (rootIface == nullptr) return;
430
Steven Morelandaf4ca712021-05-24 23:22:08 +0000431 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000432 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000434 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000435 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000436 for (auto remoteCount : remoteCounts) {
437 EXPECT_EQ(remoteCount, 1);
438 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000439
Steven Moreland798e0d12021-07-14 23:19:25 +0000440 // even though it is on another thread, shutdown races with
441 // the transaction reply being written
442 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
443 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
444 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000445 }
446
447 rootIface = nullptr;
448 rootBinder = nullptr;
449 }
450};
451
Steven Morelandc1635952021-04-01 16:20:47 +0000452enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700453 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000454 UNIX,
455 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700456 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000457};
Yifan Hong702115c2021-06-24 15:39:18 -0700458static inline std::string PrintToString(SocketType socketType) {
459 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700460 case SocketType::PRECONNECTED:
461 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000462 case SocketType::UNIX:
463 return "unix_domain_socket";
464 case SocketType::VSOCK:
465 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700466 case SocketType::INET:
467 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000468 default:
469 LOG_ALWAYS_FATAL("Unknown socket type");
470 return "";
471 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000472}
Steven Morelandda573042021-06-12 01:13:45 +0000473
Yifan Hong1deca4b2021-09-10 16:16:44 -0700474static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700475 base::unique_fd serverFd(
476 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
477 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700478 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
479 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700480
481 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
482 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700483 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
484 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700485 }
486 return serverFd;
487}
488
Frederick Mayledc07cf82022-05-26 20:30:12 +0000489class BinderRpc
490 : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000491public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000492 struct Options {
493 size_t numThreads = 1;
494 size_t numSessions = 1;
495 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700496 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000497 };
498
Yifan Hong702115c2021-06-24 15:39:18 -0700499 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000500 auto [type, security, clientVersion, serverVersion] = info.param;
501 return PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
502 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Yifan Hong702115c2021-06-24 15:39:18 -0700503 }
504
Yifan Hong1deca4b2021-09-10 16:16:44 -0700505 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
506 uint64_t length = str.length();
507 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
508 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
509 }
510
511 static inline std::string readString(android::base::borrowed_fd fd) {
512 uint64_t length;
513 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
514 std::string ret(length, '\0');
515 CHECK(android::base::ReadFully(fd, ret.data(), length));
516 return ret;
517 }
518
519 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
520 Parcel parcel;
521 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
522 writeString(fd,
523 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
524 }
525
526 template <typename T>
527 static inline T readFromFd(android::base::borrowed_fd fd) {
528 std::string data = readString(fd);
529 Parcel parcel;
530 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
531 T object;
532 CHECK_EQ(OK, object.readFromParcel(&parcel));
533 return object;
534 }
535
Steven Morelandc1635952021-04-01 16:20:47 +0000536 // This creates a new process serving an interface on a certain number of
537 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000538 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000539 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
540 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000541
Yifan Hong702115c2021-06-24 15:39:18 -0700542 SocketType socketType = std::get<0>(GetParam());
543 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000544 uint32_t clientVersion = std::get<2>(GetParam());
545 uint32_t serverVersion = std::get<3>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000546
Steven Morelandda573042021-06-12 01:13:45 +0000547 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000548 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000549
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000551 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700552 android::base::borrowed_fd readEnd) {
553 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
554 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000555
Frederick Mayledc07cf82022-05-26 20:30:12 +0000556 server->setProtocolVersion(serverVersion);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000557 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000558
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000559 unsigned int outPort = 0;
560
Steven Morelandc1635952021-04-01 16:20:47 +0000561 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700562 case SocketType::PRECONNECTED:
563 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000564 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700565 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000566 break;
567 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700568 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000569 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700570 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700571 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700572 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700573 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700574 }
Steven Morelandc1635952021-04-01 16:20:47 +0000575 default:
576 LOG_ALWAYS_FATAL("Unknown socket type");
577 }
578
Yifan Hong1deca4b2021-09-10 16:16:44 -0700579 BinderRpcTestServerInfo serverInfo;
580 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700581 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700582 writeToFd(writeEnd, serverInfo);
583 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
584
585 if (rpcSecurity == RpcSecurity::TLS) {
586 for (const auto& clientCert : clientInfo.certs) {
587 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700588 certVerifier
589 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
590 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700591 }
592 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000593
Steven Moreland611d15f2021-05-01 01:28:27 +0000594 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000595
Steven Morelandf137de92021-04-24 01:54:26 +0000596 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000597
598 // Another thread calls shutdown. Wait for it to complete.
599 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000600 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000601 };
602
Yifan Hong1deca4b2021-09-10 16:16:44 -0700603 std::vector<sp<RpcSession>> sessions;
604 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
605 for (size_t i = 0; i < options.numSessions; i++) {
606 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
607 }
608
609 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
610 BinderRpcTestClientInfo clientInfo;
611 for (const auto& session : sessions) {
612 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700613 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700614 }
615 writeToFd(ret.host.writeEnd(), clientInfo);
616
617 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700618 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700619 CHECK_NE(0, serverInfo.port);
620 }
621
622 if (rpcSecurity == RpcSecurity::TLS) {
623 const auto& serverCert = serverInfo.cert.data;
624 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700625 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
626 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700627 }
628
Steven Moreland2372f9d2021-08-05 15:42:01 -0700629 status_t status;
630
Yifan Hong1deca4b2021-09-10 16:16:44 -0700631 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000632 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700633 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700634 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000635
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000636 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700637 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700638 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700639 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700640 });
Steven Moreland4198a122021-08-03 17:37:58 -0700641 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000642 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700643 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000644 break;
645 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700646 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000647 break;
648 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700649 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000650 break;
651 default:
652 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000653 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700654 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000656 }
Steven Morelandc1635952021-04-01 16:20:47 +0000657 return ret;
658 }
659
Steven Moreland4313d7e2021-07-15 23:41:22 +0000660 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000661 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700662 .proc = createRpcTestSocketServerProcess(
663 options,
664 [&](const sp<RpcServer>& server) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000665 server->setPerSessionRootObject([&](const void* addrPtr, size_t len) {
666 // UNIX sockets with abstract addresses return
667 // sizeof(sa_family_t)==2 in addrlen
668 CHECK_GE(len, sizeof(sa_family_t));
669 const sockaddr* addr = reinterpret_cast<const sockaddr*>(addrPtr);
Steven Moreland51c44a92021-10-14 16:50:35 -0700670 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
671 switch (addr->sa_family) {
672 case AF_UNIX:
673 // nothing to save
674 break;
675 case AF_VSOCK:
676 CHECK_EQ(len, sizeof(sockaddr_vm));
677 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
678 ->svm_port;
679 break;
680 case AF_INET:
681 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700682 service->port =
683 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
684 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700685 break;
686 case AF_INET6:
687 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700688 service->port =
689 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
690 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700691 break;
692 default:
693 LOG_ALWAYS_FATAL("Unrecognized address family %d",
694 addr->sa_family);
695 }
696 service->server = server;
697 return service;
698 });
699 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000700 };
701
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000702 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000703 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
704
705 return ret;
706 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700707
708 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
709 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000710};
711
Steven Morelandc1635952021-04-01 16:20:47 +0000712TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000713 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000714 ASSERT_NE(proc.rootBinder, nullptr);
715 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
716}
717
Steven Moreland4cf688f2021-03-31 01:48:58 +0000718TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000719 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000720 ASSERT_NE(proc.rootBinder, nullptr);
721 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
722}
723
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000724TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000725 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 for (auto session : proc.proc.sessions) {
727 ASSERT_NE(nullptr, session.root);
728 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000729 }
730}
731
Steven Moreland51c44a92021-10-14 16:50:35 -0700732TEST_P(BinderRpc, SeparateRootObject) {
733 SocketType type = std::get<0>(GetParam());
734 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
735 // we can't get port numbers for unix sockets
736 return;
737 }
738
739 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
740
741 int port1 = 0;
742 EXPECT_OK(proc.rootIface->getClientPort(&port1));
743
744 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
745 int port2;
746 EXPECT_OK(rootIface2->getClientPort(&port2));
747
748 // we should have a different IBinderRpcTest object created for each
749 // session, because we use setPerSessionRootObject
750 EXPECT_NE(port1, port2);
751}
752
Steven Morelandc1635952021-04-01 16:20:47 +0000753TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000754 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 Parcel data;
756 Parcel reply;
757 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
758}
759
Steven Moreland67753c32021-04-02 18:45:19 +0000760TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700761 auto proc1 = createRpcTestSocketServerProcess({});
762 auto proc2 = createRpcTestSocketServerProcess({});
763
764 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000765
766 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700767 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000768 p1.writeInt32(3);
769
Frederick Maylea4ed5672022-06-17 22:03:38 +0000770 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700771 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
772
Steven Moreland67753c32021-04-02 18:45:19 +0000773 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700774 p2.markForBinder(proc2.rootBinder);
775 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000776
777 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
778 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
779}
780
Steven Morelandc1635952021-04-01 16:20:47 +0000781TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000782 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000783 Parcel data;
784 data.markForBinder(proc.rootBinder);
785 Parcel reply;
786 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
787}
788
Steven Morelandc1635952021-04-01 16:20:47 +0000789TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000790 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 EXPECT_OK(proc.rootIface->sendString("asdf"));
792}
793
Steven Morelandc1635952021-04-01 16:20:47 +0000794TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000795 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000796 std::string doubled;
797 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
798 EXPECT_EQ("cool cool ", doubled);
799}
800
Steven Morelandc1635952021-04-01 16:20:47 +0000801TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000802 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000803 std::string single = std::string(1024, 'a');
804 std::string doubled;
805 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
806 EXPECT_EQ(single + single, doubled);
807}
808
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000809TEST_P(BinderRpc, InvalidNullBinderReturn) {
810 auto proc = createRpcTestSocketServerProcess({});
811
812 sp<IBinder> outBinder;
813 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
814}
815
Steven Morelandc1635952021-04-01 16:20:47 +0000816TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000817 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000818
819 int32_t pingResult;
820 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
821 EXPECT_EQ(OK, pingResult);
822
823 EXPECT_EQ(0, MyBinderRpcSession::gNum);
824}
825
Steven Morelandc1635952021-04-01 16:20:47 +0000826TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000827 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000828
829 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
830 sp<IBinder> outBinder;
831 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
832 EXPECT_EQ(inBinder, outBinder);
833
834 wp<IBinder> weak = inBinder;
835 inBinder = nullptr;
836 outBinder = nullptr;
837
838 // Force reading a reply, to process any pending dec refs from the other
839 // process (the other process will process dec refs there before processing
840 // the ping here).
841 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
842
843 EXPECT_EQ(nullptr, weak.promote());
844
845 EXPECT_EQ(0, MyBinderRpcSession::gNum);
846}
847
Steven Morelandc1635952021-04-01 16:20:47 +0000848TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000849 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000850
851 sp<IBinderRpcSession> session;
852 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
853
854 sp<IBinder> inBinder = IInterface::asBinder(session);
855 sp<IBinder> outBinder;
856 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
857 EXPECT_EQ(inBinder, outBinder);
858
859 wp<IBinder> weak = inBinder;
860 session = nullptr;
861 inBinder = nullptr;
862 outBinder = nullptr;
863
864 // Force reading a reply, to process any pending dec refs from the other
865 // process (the other process will process dec refs there before processing
866 // the ping here).
867 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
868
869 EXPECT_EQ(nullptr, weak.promote());
870}
871
Steven Morelandc1635952021-04-01 16:20:47 +0000872TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000873 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000874
875 sp<IBinder> outBinder;
876 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
877 EXPECT_EQ(nullptr, outBinder);
878}
879
Steven Morelandc1635952021-04-01 16:20:47 +0000880TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000881 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000882
883 IBinder* ptr = nullptr;
884 {
885 sp<IBinder> binder = new BBinder();
886 ptr = binder.get();
887 EXPECT_OK(proc.rootIface->holdBinder(binder));
888 }
889
890 sp<IBinder> held;
891 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
892
893 EXPECT_EQ(held.get(), ptr);
894
895 // stop holding binder, because we test to make sure references are cleaned
896 // up
897 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
898 // and flush ref counts
899 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
900}
901
902// START TESTS FOR LIMITATIONS OF SOCKET BINDER
903// These are behavioral differences form regular binder, where certain usecases
904// aren't supported.
905
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000906TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000907 auto proc1 = createRpcTestSocketServerProcess({});
908 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000909
910 sp<IBinder> outBinder;
911 EXPECT_EQ(INVALID_OPERATION,
912 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
913}
914
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000915TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000916 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000917
918 sp<IBinder> outBinder;
919 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000920 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000921 .transactionError());
922}
923
Steven Morelandc1635952021-04-01 16:20:47 +0000924TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000925 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000926
927 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
928 sp<IBinder> outBinder;
929 EXPECT_EQ(INVALID_OPERATION,
930 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
931}
932
Steven Morelandc1635952021-04-01 16:20:47 +0000933TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000935
936 // for historical reasons, IServiceManager interface only returns the
937 // exception code
938 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
939 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
940}
941
942// END TESTS FOR LIMITATIONS OF SOCKET BINDER
943
Steven Morelandc1635952021-04-01 16:20:47 +0000944TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000945 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000946
947 sp<IBinder> outBinder;
948 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
949 EXPECT_EQ(proc.rootBinder, outBinder);
950}
951
Steven Morelandc1635952021-04-01 16:20:47 +0000952TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000953 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000954
955 auto nastyNester = sp<MyBinderRpcTest>::make();
956 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
957
958 wp<IBinder> weak = nastyNester;
959 nastyNester = nullptr;
960 EXPECT_EQ(nullptr, weak.promote());
961}
962
Steven Morelandc1635952021-04-01 16:20:47 +0000963TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000964 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000965
966 sp<IBinder> a;
967 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
968
969 sp<IBinder> b;
970 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
971
972 EXPECT_EQ(a, b);
973}
974
Steven Morelandc1635952021-04-01 16:20:47 +0000975TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000976 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000977
978 sp<IBinder> a;
979 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
980 wp<IBinder> weak = a;
981 a = nullptr;
982
983 sp<IBinder> b;
984 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
985
986 // this is the wrong behavior, since BpBinder
987 // doesn't implement onIncStrongAttempted
988 // but make sure there is no crash
989 EXPECT_EQ(nullptr, weak.promote());
990
991 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
992
993 // In order to fix this:
994 // - need to have incStrongAttempted reflected across IPC boundary (wait for
995 // response to promote - round trip...)
996 // - sendOnLastWeakRef, to delete entries out of RpcState table
997 EXPECT_EQ(b, weak.promote());
998}
999
1000#define expectSessions(expected, iface) \
1001 do { \
1002 int session; \
1003 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
1004 EXPECT_EQ(expected, session); \
1005 } while (false)
1006
Steven Morelandc1635952021-04-01 16:20:47 +00001007TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001008 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001009
1010 sp<IBinderRpcSession> session;
1011 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
1012 std::string out;
1013 EXPECT_OK(session->getName(&out));
1014 EXPECT_EQ("aoeu", out);
1015
1016 expectSessions(1, proc.rootIface);
1017 session = nullptr;
1018 expectSessions(0, proc.rootIface);
1019}
1020
Steven Morelandc1635952021-04-01 16:20:47 +00001021TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001022 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001023
1024 std::vector<sp<IBinderRpcSession>> sessions;
1025
1026 for (size_t i = 0; i < 15; i++) {
1027 expectSessions(i, proc.rootIface);
1028 sp<IBinderRpcSession> session;
1029 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1030 sessions.push_back(session);
1031 }
1032 expectSessions(sessions.size(), proc.rootIface);
1033 for (size_t i = 0; i < sessions.size(); i++) {
1034 std::string out;
1035 EXPECT_OK(sessions.at(i)->getName(&out));
1036 EXPECT_EQ(std::to_string(i), out);
1037 }
1038 expectSessions(sessions.size(), proc.rootIface);
1039
1040 while (!sessions.empty()) {
1041 sessions.pop_back();
1042 expectSessions(sessions.size(), proc.rootIface);
1043 }
1044 expectSessions(0, proc.rootIface);
1045}
1046
1047size_t epochMillis() {
1048 using std::chrono::duration_cast;
1049 using std::chrono::milliseconds;
1050 using std::chrono::seconds;
1051 using std::chrono::system_clock;
1052 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1053}
1054
Steven Morelandc1635952021-04-01 16:20:47 +00001055TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001056 constexpr size_t kNumThreads = 10;
1057
Steven Moreland4313d7e2021-07-15 23:41:22 +00001058 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001059
1060 EXPECT_OK(proc.rootIface->lock());
1061
1062 // block all but one thread taking locks
1063 std::vector<std::thread> ts;
1064 for (size_t i = 0; i < kNumThreads - 1; i++) {
1065 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1066 }
1067
1068 usleep(100000); // give chance for calls on other threads
1069
1070 // other calls still work
1071 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1072
1073 constexpr size_t blockTimeMs = 500;
1074 size_t epochMsBefore = epochMillis();
1075 // after this, we should never see a response within this time
1076 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1077
1078 // this call should be blocked for blockTimeMs
1079 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1080
1081 size_t epochMsAfter = epochMillis();
1082 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1083
1084 for (auto& t : ts) t.join();
1085}
1086
Yifan Hong1f44f982021-10-08 17:16:47 -07001087void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1088 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001089 size_t epochMsBefore = epochMillis();
1090
1091 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001092 for (size_t i = 0; i < numCalls; i++) {
1093 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001094 }
1095
1096 for (auto& t : ts) t.join();
1097
1098 size_t epochMsAfter = epochMillis();
1099
Yifan Hong1f44f982021-10-08 17:16:47 -07001100 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001101
1102 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001103 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1104}
1105
1106TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1107 constexpr size_t kNumThreads = 10;
1108 constexpr size_t kNumCalls = kNumThreads + 3;
1109 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1110 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1111}
1112
1113TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1114 constexpr size_t kNumThreads = 20;
1115 constexpr size_t kNumOutgoingConnections = 10;
1116 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1117 auto proc = createRpcTestSocketServerProcess(
1118 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1119 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001120}
1121
Steven Morelandc1635952021-04-01 16:20:47 +00001122TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001123 constexpr size_t kNumClientThreads = 10;
1124 constexpr size_t kNumServerThreads = 10;
1125 constexpr size_t kNumCalls = 100;
1126
Steven Moreland4313d7e2021-07-15 23:41:22 +00001127 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001128
1129 std::vector<std::thread> threads;
1130 for (size_t i = 0; i < kNumClientThreads; i++) {
1131 threads.push_back(std::thread([&] {
1132 for (size_t j = 0; j < kNumCalls; j++) {
1133 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001134 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001135 EXPECT_EQ(proc.rootBinder, out);
1136 }
1137 }));
1138 }
1139
1140 for (auto& t : threads) t.join();
1141}
1142
Steven Moreland925ba0a2021-09-17 18:06:32 -07001143static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1144 std::vector<std::thread> threads;
1145 for (size_t i = 0; i < threadCount; i++) {
1146 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1147 }
1148 for (auto& t : threads) t.join();
1149}
1150
Steven Morelandc6046982021-04-20 00:49:42 +00001151TEST_P(BinderRpc, OnewayStressTest) {
1152 constexpr size_t kNumClientThreads = 10;
1153 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001154 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001155
Steven Moreland4313d7e2021-07-15 23:41:22 +00001156 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001157
1158 std::vector<std::thread> threads;
1159 for (size_t i = 0; i < kNumClientThreads; i++) {
1160 threads.push_back(std::thread([&] {
1161 for (size_t j = 0; j < kNumCalls; j++) {
1162 EXPECT_OK(proc.rootIface->sendString("a"));
1163 }
Steven Morelandc6046982021-04-20 00:49:42 +00001164 }));
1165 }
1166
1167 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001168
1169 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001170}
1171
Steven Morelandc1635952021-04-01 16:20:47 +00001172TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001173 constexpr size_t kReallyLongTimeMs = 100;
1174 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1175
Steven Moreland4313d7e2021-07-15 23:41:22 +00001176 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001177
1178 size_t epochMsBefore = epochMillis();
1179
1180 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1181
1182 size_t epochMsAfter = epochMillis();
1183 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1184}
1185
Steven Morelandc1635952021-04-01 16:20:47 +00001186TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001187 constexpr size_t kNumSleeps = 10;
1188 constexpr size_t kNumExtraServerThreads = 4;
1189 constexpr size_t kSleepMs = 50;
1190
1191 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001192 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001193
1194 EXPECT_OK(proc.rootIface->lock());
1195
Steven Moreland1c678802021-09-17 16:48:47 -07001196 size_t epochMsBefore = epochMillis();
1197
1198 // all these *Async commands should be queued on the server sequentially,
1199 // even though there are multiple threads.
1200 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001201 proc.rootIface->sleepMsAsync(kSleepMs);
1202 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001203 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1204
Steven Moreland1c678802021-09-17 16:48:47 -07001205 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001206 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001207
Steven Moreland5553ac42020-11-11 02:14:45 +00001208 size_t epochMsAfter = epochMillis();
1209
1210 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001211
Steven Moreland925ba0a2021-09-17 18:06:32 -07001212 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001213}
1214
Steven Morelandd45be622021-06-04 02:19:37 +00001215TEST_P(BinderRpc, OnewayCallExhaustion) {
1216 constexpr size_t kNumClients = 2;
1217 constexpr size_t kTooLongMs = 1000;
1218
Steven Moreland4313d7e2021-07-15 23:41:22 +00001219 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001220
1221 // Build up oneway calls on the second session to make sure it terminates
1222 // and shuts down. The first session should be unaffected (proc destructor
1223 // checks the first session).
1224 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1225
1226 std::vector<std::thread> threads;
1227 for (size_t i = 0; i < kNumClients; i++) {
1228 // one of these threads will get stuck queueing a transaction once the
1229 // socket fills up, the other will be able to fill up transactions on
1230 // this object
1231 threads.push_back(std::thread([&] {
1232 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1233 }
1234 }));
1235 }
1236 for (auto& t : threads) t.join();
1237
1238 Status status = iface->sleepMsAsync(kTooLongMs);
1239 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1240
Steven Moreland798e0d12021-07-14 23:19:25 +00001241 // now that it has died, wait for the remote session to shutdown
1242 std::vector<int32_t> remoteCounts;
1243 do {
1244 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1245 } while (remoteCounts.size() == kNumClients);
1246
Steven Morelandd45be622021-06-04 02:19:37 +00001247 // the second session should be shutdown in the other process by the time we
1248 // are able to join above (it'll only be hung up once it finishes processing
1249 // any pending commands). We need to erase this session from the record
1250 // here, so that the destructor for our session won't check that this
1251 // session is valid, but we still want it to test the other session.
1252 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1253}
1254
Steven Moreland659416d2021-05-11 00:47:50 +00001255TEST_P(BinderRpc, Callbacks) {
1256 const static std::string kTestString = "good afternoon!";
1257
Steven Morelandc7d40132021-06-10 03:42:11 +00001258 for (bool callIsOneway : {true, false}) {
1259 for (bool callbackIsOneway : {true, false}) {
1260 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001261 auto proc = createRpcTestSocketServerProcess(
1262 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001263 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001264
Steven Morelandc7d40132021-06-10 03:42:11 +00001265 if (callIsOneway) {
1266 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1267 kTestString));
1268 } else {
1269 EXPECT_OK(
1270 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1271 }
Steven Moreland659416d2021-05-11 00:47:50 +00001272
Steven Moreland03ecce62022-05-13 23:22:05 +00001273 // if both transactions are synchronous and the response is sent back on the
1274 // same thread, everything should have happened in a nested call. Otherwise,
1275 // the callback will be processed on another thread.
1276 if (callIsOneway || callbackIsOneway || delayed) {
1277 using std::literals::chrono_literals::operator""s;
1278 std::unique_lock<std::mutex> _l(cb->mMutex);
1279 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1280 }
Steven Moreland659416d2021-05-11 00:47:50 +00001281
Steven Morelandc7d40132021-06-10 03:42:11 +00001282 EXPECT_EQ(cb->mValues.size(), 1)
1283 << "callIsOneway: " << callIsOneway
1284 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1285 if (cb->mValues.empty()) continue;
1286 EXPECT_EQ(cb->mValues.at(0), kTestString)
1287 << "callIsOneway: " << callIsOneway
1288 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001289
Steven Morelandc7d40132021-06-10 03:42:11 +00001290 // since we are severing the connection, we need to go ahead and
1291 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001292 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1293 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1294 }
Steven Moreland659416d2021-05-11 00:47:50 +00001295
Steven Moreland1b304292021-07-15 22:59:34 +00001296 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001297 // need to manually shut it down
1298 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001299
Steven Morelandc7d40132021-06-10 03:42:11 +00001300 proc.expectAlreadyShutdown = true;
1301 }
Steven Moreland659416d2021-05-11 00:47:50 +00001302 }
1303 }
1304}
1305
Steven Moreland195edb82021-06-08 02:44:39 +00001306TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001307 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001308 auto cb = sp<MyBinderRpcCallback>::make();
1309
1310 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1311 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1312}
1313
Steven Morelandc1635952021-04-01 16:20:47 +00001314TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001315 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001316 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001317
1318 // make sure there is some state during crash
1319 // 1. we hold their binder
1320 sp<IBinderRpcSession> session;
1321 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1322 // 2. they hold our binder
1323 sp<IBinder> binder = new BBinder();
1324 EXPECT_OK(proc.rootIface->holdBinder(binder));
1325
1326 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1327 << "Do death cleanup: " << doDeathCleanup;
1328
Steven Morelandaf4ca712021-05-24 23:22:08 +00001329 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001330 }
1331}
1332
Steven Morelandd7302072021-05-15 01:32:04 +00001333TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Morelanda83191d2021-10-27 10:14:53 -07001334 bool okToFork = ProcessState::selfOrNull() == nullptr;
1335
Steven Moreland4313d7e2021-07-15 23:41:22 +00001336 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001337
Steven Morelanda83191d2021-10-27 10:14:53 -07001338 // If this process has used ProcessState already, then the forked process
1339 // cannot use it at all. If this process hasn't used it (depending on the
1340 // order tests are run), then the forked process can use it, and we'll only
1341 // catch the invalid usage the second time. Such is the burden of global
1342 // state!
1343 if (okToFork) {
1344 // we can't allocate IPCThreadState so actually the first time should
1345 // succeed :(
1346 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1347 }
Steven Morelandd7302072021-05-15 01:32:04 +00001348
1349 // second time! we catch the error :)
1350 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1351
Steven Morelandaf4ca712021-05-24 23:22:08 +00001352 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001353}
1354
Steven Moreland37aff182021-03-26 02:04:16 +00001355TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001356 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001357
1358 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1359 ASSERT_NE(binder, nullptr);
1360
1361 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1362}
1363
1364TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001365 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001366
1367 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1368 ASSERT_NE(binder, nullptr);
1369
1370 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1371 ASSERT_NE(ndkBinder, nullptr);
1372
1373 std::string out;
1374 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1375 ASSERT_TRUE(status.isOk()) << status.getDescription();
1376 ASSERT_EQ("aoeuaoeu", out);
1377}
1378
Steven Moreland5553ac42020-11-11 02:14:45 +00001379ssize_t countFds() {
1380 DIR* dir = opendir("/proc/self/fd/");
1381 if (dir == nullptr) return -1;
1382 ssize_t ret = 0;
1383 dirent* ent;
1384 while ((ent = readdir(dir)) != nullptr) ret++;
1385 closedir(dir);
1386 return ret;
1387}
1388
Steven Morelandc1635952021-04-01 16:20:47 +00001389TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001390 ssize_t beforeFds = countFds();
1391 ASSERT_GE(beforeFds, 0);
1392 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001393 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001394 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1395 }
1396 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1397}
1398
Devin Moore800b2252021-10-15 16:22:57 +00001399TEST_P(BinderRpc, AidlDelegatorTest) {
1400 auto proc = createRpcTestSocketServerProcess({});
1401 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1402 ASSERT_NE(nullptr, myDelegator);
1403
1404 std::string doubled;
1405 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1406 EXPECT_EQ("cool cool ", doubled);
1407}
1408
Steven Morelandda573042021-06-12 01:13:45 +00001409static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001410 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001411 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001412 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001413 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1414 if (status == -EAFNOSUPPORT) {
1415 return false;
1416 }
1417 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1418 }
Steven Morelandda573042021-06-12 01:13:45 +00001419 server->start();
1420
Yifan Hongfdd9f692021-09-09 15:12:52 -07001421 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001422 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001423 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001424 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1425 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001426}
1427
Yifan Hong1deca4b2021-09-10 16:16:44 -07001428static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1429 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1430
1431 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001432
1433 static bool hasVsockLoopback = testSupportVsockLoopback();
1434
1435 if (hasVsockLoopback) {
1436 ret.push_back(SocketType::VSOCK);
1437 }
1438
1439 return ret;
1440}
1441
Frederick Mayledc07cf82022-05-26 20:30:12 +00001442static std::vector<uint32_t> testVersions() {
1443 std::vector<uint32_t> versions;
1444 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1445 versions.push_back(i);
1446 }
1447 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1448 return versions;
1449}
1450
Yifan Hong702115c2021-06-24 15:39:18 -07001451INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1452 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001453 ::testing::ValuesIn(RpcSecurityValues()),
1454 ::testing::ValuesIn(testVersions()),
1455 ::testing::ValuesIn(testVersions())),
Yifan Hong702115c2021-06-24 15:39:18 -07001456 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001457
Yifan Hong702115c2021-06-24 15:39:18 -07001458class BinderRpcServerRootObject
1459 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001460
1461TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1462 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1463 auto setRootObject = [](bool isStrong) -> SetFn {
1464 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1465 };
1466
Yifan Hong702115c2021-06-24 15:39:18 -07001467 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1468 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001469 auto binder1 = sp<BBinder>::make();
1470 IBinder* binderRaw1 = binder1.get();
1471 setRootObject(isStrong1)(server.get(), binder1);
1472 EXPECT_EQ(binderRaw1, server->getRootObject());
1473 binder1.clear();
1474 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1475
1476 auto binder2 = sp<BBinder>::make();
1477 IBinder* binderRaw2 = binder2.get();
1478 setRootObject(isStrong2)(server.get(), binder2);
1479 EXPECT_EQ(binderRaw2, server->getRootObject());
1480 binder2.clear();
1481 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1482}
1483
1484INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001485 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1486 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001487
Yifan Hong1a235852021-05-13 16:07:47 -07001488class OneOffSignal {
1489public:
1490 // If notify() was previously called, or is called within |duration|, return true; else false.
1491 template <typename R, typename P>
1492 bool wait(std::chrono::duration<R, P> duration) {
1493 std::unique_lock<std::mutex> lock(mMutex);
1494 return mCv.wait_for(lock, duration, [this] { return mValue; });
1495 }
1496 void notify() {
1497 std::unique_lock<std::mutex> lock(mMutex);
1498 mValue = true;
1499 lock.unlock();
1500 mCv.notify_all();
1501 }
1502
1503private:
1504 std::mutex mMutex;
1505 std::condition_variable mCv;
1506 bool mValue = false;
1507};
1508
Frederick Mayledc07cf82022-05-26 20:30:12 +00001509TEST_P(BinderRpcServerOnly, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001510 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001511 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1512 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001513 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001514 auto joinEnds = std::make_shared<OneOffSignal>();
1515
1516 // If things are broken and the thread never stops, don't block other tests. Because the thread
1517 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1518 // shared pointers are passed.
1519 std::thread([server, joinEnds] {
1520 server->join();
1521 joinEnds->notify();
1522 }).detach();
1523
1524 bool shutdown = false;
1525 for (int i = 0; i < 10 && !shutdown; i++) {
1526 usleep(300 * 1000); // 300ms; total 3s
1527 if (server->shutdown()) shutdown = true;
1528 }
1529 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1530
1531 ASSERT_TRUE(joinEnds->wait(2s))
1532 << "After server->shutdown() returns true, join() did not stop after 2s";
1533}
1534
Yifan Hong194acf22021-06-29 18:44:56 -07001535TEST(BinderRpc, Java) {
1536#if !defined(__ANDROID__)
1537 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1538 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1539 "to binderHostDeviceTest. Hence, just disable this test on host.";
1540#endif // !__ANDROID__
1541 sp<IServiceManager> sm = defaultServiceManager();
1542 ASSERT_NE(nullptr, sm);
1543 // Any Java service with non-empty getInterfaceDescriptor() would do.
1544 // Let's pick batteryproperties.
1545 auto binder = sm->checkService(String16("batteryproperties"));
1546 ASSERT_NE(nullptr, binder);
1547 auto descriptor = binder->getInterfaceDescriptor();
1548 ASSERT_GE(descriptor.size(), 0);
1549 ASSERT_EQ(OK, binder->pingBinder());
1550
1551 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001552 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001553 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001554 auto socket = rpcServer->releaseServer();
1555
1556 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001557 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1558
Yifan Honge3caaf22022-01-12 14:46:56 -08001559 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1560 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001561 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001562 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1563 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001564 << statusToString(setRpcClientDebugStatus);
1565 GTEST_SKIP();
1566 }
1567
1568 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001569
1570 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001571 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001572 auto rpcBinder = rpcSession->getRootObject();
1573 ASSERT_NE(nullptr, rpcBinder);
1574
1575 ASSERT_EQ(OK, rpcBinder->pingBinder());
1576
1577 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1578 << "getInterfaceDescriptor should not crash system_server";
1579 ASSERT_EQ(OK, rpcBinder->pingBinder());
1580}
1581
Frederick Mayledc07cf82022-05-26 20:30:12 +00001582INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1583 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1584 ::testing::ValuesIn(testVersions())),
1585 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001586
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001587class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001588public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001589 // Only parameterized only server version because `RpcSession` is bypassed
1590 // in the client half of the tests.
1591 using Param =
1592 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001593 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001594
1595 // A server that handles client socket connections.
1596 class Server {
1597 public:
1598 explicit Server() {}
1599 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001600 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001601 [[nodiscard]] AssertionResult setUp(
1602 const Param& param,
1603 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001604 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001605 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001606 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001607 switch (socketType) {
1608 case SocketType::PRECONNECTED: {
1609 return AssertionFailure() << "Not supported by this test";
1610 } break;
1611 case SocketType::UNIX: {
1612 auto addr = allocateSocketAddress();
1613 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1614 if (status != OK) {
1615 return AssertionFailure()
1616 << "setupUnixDomainServer: " << statusToString(status);
1617 }
1618 mConnectToServer = [addr] {
1619 return connectTo(UnixSocketAddress(addr.c_str()));
1620 };
1621 } break;
1622 case SocketType::VSOCK: {
1623 auto port = allocateVsockPort();
1624 auto status = rpcServer->setupVsockServer(port);
1625 if (status != OK) {
1626 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1627 }
1628 mConnectToServer = [port] {
1629 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1630 };
1631 } break;
1632 case SocketType::INET: {
1633 unsigned int port;
1634 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1635 if (status != OK) {
1636 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1637 }
1638 mConnectToServer = [port] {
1639 const char* addr = kLocalInetAddress;
1640 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1641 if (aiStart == nullptr) return base::unique_fd{};
1642 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1643 auto fd = connectTo(
1644 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1645 if (fd.ok()) return fd;
1646 }
1647 ALOGE("None of the socket address resolved for %s:%u can be connected",
1648 addr, port);
1649 return base::unique_fd{};
1650 };
1651 }
1652 }
1653 mFd = rpcServer->releaseServer();
1654 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001655 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001656 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1657 mSetup = true;
1658 return AssertionSuccess();
1659 }
1660 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1661 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1662 return mCertVerifier;
1663 }
1664 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1665 void start() {
1666 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1667 mThread = std::make_unique<std::thread>(&Server::run, this);
1668 }
1669 void run() {
1670 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1671
1672 std::vector<std::thread> threads;
1673 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1674 base::unique_fd acceptedFd(
1675 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1676 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1677 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1678 }
1679
1680 for (auto& thread : threads) thread.join();
1681 }
1682 void handleOne(android::base::unique_fd acceptedFd) {
1683 ASSERT_TRUE(acceptedFd.ok());
1684 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1685 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001686 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001687 }
Yifan Honge07d2732021-09-13 21:59:14 -07001688 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001689 shutdown();
1690 join();
1691 }
1692 void shutdown() { mFdTrigger->trigger(); }
1693
1694 void setPostConnect(
1695 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1696 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001697 }
1698
1699 private:
1700 std::unique_ptr<std::thread> mThread;
1701 ConnectToServer mConnectToServer;
1702 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1703 base::unique_fd mFd;
1704 std::unique_ptr<RpcTransportCtx> mCtx;
1705 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1706 std::make_shared<RpcCertificateVerifierSimple>();
1707 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001708 // The function invoked after connection and handshake. By default, it is
1709 // |defaultPostConnect| that sends |kMessage| to the client.
1710 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1711 Server::defaultPostConnect;
1712
1713 void join() {
1714 if (mThread != nullptr) {
1715 mThread->join();
1716 mThread = nullptr;
1717 }
1718 }
1719
1720 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1721 FdTrigger* fdTrigger) {
1722 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001723 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001724 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1725 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001726 if (status != OK) return AssertionFailure() << statusToString(status);
1727 return AssertionSuccess();
1728 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001729 };
1730
1731 class Client {
1732 public:
1733 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1734 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001735 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001736 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1737 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738 mFdTrigger = FdTrigger::make();
1739 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1740 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1741 return AssertionSuccess();
1742 }
1743 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1744 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1745 return mCertVerifier;
1746 }
Yifan Hong67519322021-09-13 18:51:16 -07001747 // connect() and do handshake
1748 bool setUpTransport() {
1749 mFd = mConnectToServer();
1750 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1751 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1752 return mClientTransport != nullptr;
1753 }
1754 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1755 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1756 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001757 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001758 status_t readStatus =
1759 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
1760 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001761 if (readStatus != OK) {
1762 return AssertionFailure() << statusToString(readStatus);
1763 }
1764 if (readMessage != expectedMessage) {
1765 return AssertionFailure()
1766 << "Expected " << expectedMessage << ", actual " << readMessage;
1767 }
1768 return AssertionSuccess();
1769 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001770 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001771 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001772 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1773 return;
1774 }
1775 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001776 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001777 }
1778
1779 private:
1780 ConnectToServer mConnectToServer;
1781 base::unique_fd mFd;
1782 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1783 std::unique_ptr<RpcTransportCtx> mCtx;
1784 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1785 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001786 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787 };
1788
1789 // Make A trust B.
1790 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001791 static status_t trust(RpcSecurity rpcSecurity,
1792 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1793 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001795 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1796 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1797 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001798 }
1799
1800 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001801};
1802
1803class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1804public:
1805 using Server = RpcTransportTestUtils::Server;
1806 using Client = RpcTransportTestUtils::Client;
1807 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001808 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001809 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1810 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001811 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001812 return ret;
1813 }
1814 static std::vector<ParamType> getRpcTranportTestParams() {
1815 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001816 for (auto serverVersion : testVersions()) {
1817 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1818 for (auto rpcSecurity : RpcSecurityValues()) {
1819 switch (rpcSecurity) {
1820 case RpcSecurity::RAW: {
1821 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1822 } break;
1823 case RpcSecurity::TLS: {
1824 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1825 serverVersion);
1826 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1827 serverVersion);
1828 } break;
1829 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001830 }
1831 }
1832 }
1833 return ret;
1834 }
1835 template <typename A, typename B>
1836 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001837 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1838 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1840 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001841};
1842
1843TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001844 auto server = std::make_unique<Server>();
1845 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001846
1847 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001849
1850 ASSERT_EQ(OK, trust(&client, server));
1851 ASSERT_EQ(OK, trust(server, &client));
1852
1853 server->start();
1854 client.run();
1855}
1856
1857TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001858 auto server = std::make_unique<Server>();
1859 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001860
1861 std::vector<Client> clients;
1862 for (int i = 0; i < 2; i++) {
1863 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001864 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001865 ASSERT_EQ(OK, trust(&client, server));
1866 ASSERT_EQ(OK, trust(server, &client));
1867 }
1868
1869 server->start();
1870 for (auto& client : clients) client.run();
1871}
1872
1873TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001874 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1875 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001876
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001877 auto untrustedServer = std::make_unique<Server>();
1878 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001879
1880 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001881 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001882
1883 ASSERT_EQ(OK, trust(untrustedServer, &client));
1884
1885 untrustedServer->start();
1886
1887 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1888 // the client can't verify the server's identity.
1889 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1890 client.run(handshakeOk);
1891}
1892TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001893 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1894 (void)serverVersion;
1895
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001896 auto validServer = std::make_unique<Server>();
1897 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001898
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001899 auto maliciousServer = std::make_unique<Server>();
1900 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001901
1902 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001903 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904
1905 ASSERT_EQ(OK, trust(&client, validServer));
1906 ASSERT_EQ(OK, trust(validServer, &client));
1907 ASSERT_EQ(OK, trust(maliciousServer, &client));
1908
1909 maliciousServer->start();
1910
1911 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1912 // the client can't verify the server's identity.
1913 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1914 client.run(handshakeOk);
1915}
1916
1917TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001918 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1919 (void)serverVersion;
1920
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001921 auto server = std::make_unique<Server>();
1922 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001923
1924 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001925 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001926
1927 ASSERT_EQ(OK, trust(&client, server));
1928
1929 server->start();
1930
1931 // For TLS, Client should be able to verify server's identity, so client should see
1932 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1933 // identity and should drop the connection, so client shouldn't be able to read anything.
1934 bool readOk = rpcSecurity != RpcSecurity::TLS;
1935 client.run(true, readOk);
1936}
1937
1938TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001939 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1940 (void)serverVersion;
1941
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001942 auto server = std::make_unique<Server>();
1943 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001944
1945 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001946 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001947 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001948 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001949
1950 ASSERT_EQ(OK, trust(&validClient, server));
1951 ASSERT_EQ(OK, trust(&maliciousClient, server));
1952
1953 server->start();
1954
1955 // See UntrustedClient.
1956 bool readOk = rpcSecurity != RpcSecurity::TLS;
1957 maliciousClient.run(true, readOk);
1958}
1959
Yifan Hong67519322021-09-13 18:51:16 -07001960TEST_P(RpcTransportTest, Trigger) {
1961 std::string msg2 = ", world!";
1962 std::mutex writeMutex;
1963 std::condition_variable writeCv;
1964 bool shouldContinueWriting = false;
1965 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001966 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001967 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001968 auto status =
1969 serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001970 if (status != OK) return AssertionFailure() << statusToString(status);
1971
1972 {
1973 std::unique_lock<std::mutex> lock(writeMutex);
1974 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1975 return AssertionFailure() << "write barrier not cleared in time!";
1976 }
1977 }
1978
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001979 iovec msg2Iov{msg2.data(), msg2.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001980 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt);
Steven Morelandc591b472021-09-16 13:56:11 -07001981 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001982 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001983 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001984 << statusToString(status);
1985 return AssertionSuccess();
1986 };
1987
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001988 auto server = std::make_unique<Server>();
1989 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001990
1991 // Set up client
1992 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001993 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001994
1995 // Exchange keys
1996 ASSERT_EQ(OK, trust(&client, server));
1997 ASSERT_EQ(OK, trust(server, &client));
1998
1999 server->setPostConnect(serverPostConnect);
2000
Yifan Hong67519322021-09-13 18:51:16 -07002001 server->start();
2002 // connect() to server and do handshake
2003 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002004 // read the first message. This ensures that server has finished handshake and start handling
2005 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002006 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002007 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2008 // write is on an FdTrigger that has been shut down.
2009 server->shutdown();
2010 // Continues server thread to write the second message.
2011 {
Yifan Hong22211f82021-09-14 12:32:25 -07002012 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002013 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002014 }
Yifan Hong22211f82021-09-14 12:32:25 -07002015 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002016 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002017 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002018 // On the client side, second read fails with DEAD_OBJECT
2019 ASSERT_FALSE(client.readMessage(msg2));
2020}
2021
Yifan Hong1deca4b2021-09-10 16:16:44 -07002022INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002023 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002024 RpcTransportTest::PrintParamInfo);
2025
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002027 : public testing::TestWithParam<
2028 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002029public:
2030 template <typename A, typename B>
2031 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002032 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2033 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002034 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2035 }
2036 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002037 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2038 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2039 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002040 };
2041};
2042
2043TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002044 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002045
2046 std::vector<uint8_t> pkeyData, certData;
2047 {
2048 auto pkey = makeKeyPairForSelfSignedCert();
2049 ASSERT_NE(nullptr, pkey);
2050 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2051 ASSERT_NE(nullptr, cert);
2052 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2053 certData = serializeCertificate(cert.get(), certificateFormat);
2054 }
2055
2056 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2057 auto desCert = deserializeCertificate(certData, certificateFormat);
2058 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002059 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2060 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002061
2062 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2063 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2064
2065 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2066 ASSERT_TRUE(client.setUp(utilsParam));
2067
2068 ASSERT_EQ(OK, trust(&client, server));
2069 ASSERT_EQ(OK, trust(server, &client));
2070
2071 server->start();
2072 client.run();
2073}
2074
2075INSTANTIATE_TEST_CASE_P(
2076 BinderRpc, RpcTransportTlsKeyTest,
2077 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2078 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002079 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2080 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002081 RpcTransportTlsKeyTest::PrintParamInfo);
2082
Steven Morelandc1635952021-04-01 16:20:47 +00002083} // namespace android
2084
2085int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002086 ::testing::InitGoogleTest(&argc, argv);
2087 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002088
Steven Moreland5553ac42020-11-11 02:14:45 +00002089 return RUN_ALL_TESTS();
2090}