blob: 0d5112d29adbf986be031aebd48c9ebb22a0d407 [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
Yifan Hong702115c2021-06-24 15:39:18 -0700102class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
103public:
104 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
105 return newFactory(info.param)->toCString();
106 }
107};
108
109TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700110 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
111 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -0700112 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700113 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
114 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700115 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700116 ASSERT_TRUE(server->hasServer());
117 base::unique_fd retrieved = server->releaseServer();
118 ASSERT_FALSE(server->hasServer());
119 ASSERT_EQ(sinkFd, retrieved.get());
120}
121
Steven Morelandbf57bce2021-07-26 15:26:12 -0700122TEST(BinderRpc, CannotUseNextWireVersion) {
123 auto session = RpcSession::make();
124 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
125 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
126 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
127 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
128}
129
130TEST(BinderRpc, CanUseExperimentalWireVersion) {
131 auto session = RpcSession::make();
132 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
133}
134
Steven Moreland5553ac42020-11-11 02:14:45 +0000135using android::binder::Status;
136
137#define EXPECT_OK(status) \
138 do { \
139 Status stat = (status); \
140 EXPECT_TRUE(stat.isOk()) << stat; \
141 } while (false)
142
143class MyBinderRpcSession : public BnBinderRpcSession {
144public:
145 static std::atomic<int32_t> gNum;
146
147 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
148 Status getName(std::string* name) override {
149 *name = mName;
150 return Status::ok();
151 }
152 ~MyBinderRpcSession() { gNum--; }
153
154private:
155 std::string mName;
156};
157std::atomic<int32_t> MyBinderRpcSession::gNum;
158
Steven Moreland659416d2021-05-11 00:47:50 +0000159class MyBinderRpcCallback : public BnBinderRpcCallback {
160 Status sendCallback(const std::string& value) {
161 std::unique_lock _l(mMutex);
162 mValues.push_back(value);
163 _l.unlock();
164 mCv.notify_one();
165 return Status::ok();
166 }
167 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
168
169public:
170 std::mutex mMutex;
171 std::condition_variable mCv;
172 std::vector<std::string> mValues;
173};
174
Steven Moreland5553ac42020-11-11 02:14:45 +0000175class MyBinderRpcTest : public BnBinderRpcTest {
176public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000177 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000178
179 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000180 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181 return Status::ok();
182 }
183 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000184 *strstr = str + str;
185 return Status::ok();
186 }
Steven Moreland736664b2021-05-01 04:27:25 +0000187 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000188 sp<RpcServer> spServer = server.promote();
189 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000190 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
191 }
Steven Moreland736664b2021-05-01 04:27:25 +0000192 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000193 for (auto session : spServer->listSessions()) {
194 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000195 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000196 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 return Status::ok();
198 }
199 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
200 if (binder == nullptr) {
201 std::cout << "Received null binder!" << std::endl;
202 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
203 }
204 *out = binder->pingBinder();
205 return Status::ok();
206 }
207 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
208 *out = binder;
209 return Status::ok();
210 }
211 static sp<IBinder> mHeldBinder;
212 Status holdBinder(const sp<IBinder>& binder) override {
213 mHeldBinder = binder;
214 return Status::ok();
215 }
216 Status getHeldBinder(sp<IBinder>* held) override {
217 *held = mHeldBinder;
218 return Status::ok();
219 }
220 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
221 if (count <= 0) return Status::ok();
222 return binder->nestMe(this, count - 1);
223 }
224 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
225 static sp<IBinder> binder = new BBinder;
226 *out = binder;
227 return Status::ok();
228 }
229 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
230 *out = new MyBinderRpcSession(name);
231 return Status::ok();
232 }
233 Status getNumOpenSessions(int32_t* out) override {
234 *out = MyBinderRpcSession::gNum;
235 return Status::ok();
236 }
237
238 std::mutex blockMutex;
239 Status lock() override {
240 blockMutex.lock();
241 return Status::ok();
242 }
243 Status unlockInMsAsync(int32_t ms) override {
244 usleep(ms * 1000);
245 blockMutex.unlock();
246 return Status::ok();
247 }
248 Status lockUnlock() override {
249 std::lock_guard<std::mutex> _l(blockMutex);
250 return Status::ok();
251 }
252
253 Status sleepMs(int32_t ms) override {
254 usleep(ms * 1000);
255 return Status::ok();
256 }
257
258 Status sleepMsAsync(int32_t ms) override {
259 // In-process binder calls are asynchronous, but the call to this method
260 // is synchronous wrt its client. This in/out-process threading model
261 // diffentiation is a classic binder leaky abstraction (for better or
262 // worse) and is preserved here the way binder sockets plugs itself
263 // into BpBinder, as nothing is changed at the higher levels
264 // (IInterface) which result in this behavior.
265 return sleepMs(ms);
266 }
267
Steven Moreland659416d2021-05-11 00:47:50 +0000268 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
269 const std::string& value) override {
270 if (callback == nullptr) {
271 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
272 }
273
274 if (delayed) {
275 std::thread([=]() {
276 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000277 Status status = doCallback(callback, oneway, false, value);
278 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000279 }).detach();
280 return Status::ok();
281 }
282
283 if (oneway) {
284 return callback->sendOnewayCallback(value);
285 }
286
287 return callback->sendCallback(value);
288 }
289
Steven Morelandc7d40132021-06-10 03:42:11 +0000290 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
291 const std::string& value) override {
292 return doCallback(callback, oneway, delayed, value);
293 }
294
Steven Moreland5553ac42020-11-11 02:14:45 +0000295 Status die(bool cleanup) override {
296 if (cleanup) {
297 exit(1);
298 } else {
299 _exit(1);
300 }
301 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000302
303 Status scheduleShutdown() override {
304 sp<RpcServer> strongServer = server.promote();
305 if (strongServer == nullptr) {
306 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
307 }
308 std::thread([=] {
309 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
310 }).detach();
311 return Status::ok();
312 }
313
Steven Morelandd7302072021-05-15 01:32:04 +0000314 Status useKernelBinderCallingId() override {
315 // this is WRONG! It does not make sense when using RPC binder, and
316 // because it is SO wrong, and so much code calls this, it should abort!
317
318 (void)IPCThreadState::self()->getCallingPid();
319 return Status::ok();
320 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000321};
322sp<IBinder> MyBinderRpcTest::mHeldBinder;
323
324class Process {
325public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700326 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700327 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
328 android::base::borrowed_fd /* readEnd */)>& f) {
329 android::base::unique_fd childWriteEnd;
330 android::base::unique_fd childReadEnd;
331 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
332 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000333 if (0 == (mPid = fork())) {
334 // racey: assume parent doesn't crash before this is set
335 prctl(PR_SET_PDEATHSIG, SIGHUP);
336
Yifan Hong1deca4b2021-09-10 16:16:44 -0700337 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000338
339 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000340 }
341 }
342 ~Process() {
343 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000344 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000345 }
346 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700347 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700348 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000349
350private:
351 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700352 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700353 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000354};
355
356static std::string allocateSocketAddress() {
357 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000358 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700359 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
360 unlink(ret.c_str());
361 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000362};
363
Steven Morelandda573042021-06-12 01:13:45 +0000364static unsigned int allocateVsockPort() {
365 static unsigned int vsockPort = 3456;
366 return vsockPort++;
367}
368
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000369struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000370 // reference to process hosting a socket server
371 Process host;
372
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000373 struct SessionInfo {
374 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000375 sp<IBinder> root;
376 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000377
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000378 // client session objects associated with other process
379 // each one represents a separate session
380 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 ProcessSession(ProcessSession&&) = default;
383 ~ProcessSession() {
384 for (auto& session : sessions) {
385 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000386 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000387
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000388 for (auto& info : sessions) {
389 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000390
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391 EXPECT_NE(nullptr, session);
392 EXPECT_NE(nullptr, session->state());
393 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000394
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 wp<RpcSession> weakSession = session;
396 session = nullptr;
397 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000398 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000399 }
400};
401
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000403// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404struct BinderRpcTestProcessSession {
405 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000406
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000408 sp<IBinder> rootBinder;
409
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000411 sp<IBinderRpcTest> rootIface;
412
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000413 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000414 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000415
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
417 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000418 EXPECT_NE(nullptr, rootIface);
419 if (rootIface == nullptr) return;
420
Steven Morelandaf4ca712021-05-24 23:22:08 +0000421 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000422 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000423 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000424 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000425 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000426 for (auto remoteCount : remoteCounts) {
427 EXPECT_EQ(remoteCount, 1);
428 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000429
Steven Moreland798e0d12021-07-14 23:19:25 +0000430 // even though it is on another thread, shutdown races with
431 // the transaction reply being written
432 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
433 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
434 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000435 }
436
437 rootIface = nullptr;
438 rootBinder = nullptr;
439 }
440};
441
Steven Morelandc1635952021-04-01 16:20:47 +0000442enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700443 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000444 UNIX,
445 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700446 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000447};
Yifan Hong702115c2021-06-24 15:39:18 -0700448static inline std::string PrintToString(SocketType socketType) {
449 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700450 case SocketType::PRECONNECTED:
451 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000452 case SocketType::UNIX:
453 return "unix_domain_socket";
454 case SocketType::VSOCK:
455 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700456 case SocketType::INET:
457 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000458 default:
459 LOG_ALWAYS_FATAL("Unknown socket type");
460 return "";
461 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000462}
Steven Morelandda573042021-06-12 01:13:45 +0000463
Yifan Hong1deca4b2021-09-10 16:16:44 -0700464static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700465 base::unique_fd serverFd(
466 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
467 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700468 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
469 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700470
471 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
472 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700473 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
474 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700475 }
476 return serverFd;
477}
478
Yifan Hong702115c2021-06-24 15:39:18 -0700479class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000480public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000481 struct Options {
482 size_t numThreads = 1;
483 size_t numSessions = 1;
484 size_t numIncomingConnections = 0;
485 };
486
Yifan Hong702115c2021-06-24 15:39:18 -0700487 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
488 auto [type, security] = info.param;
489 return PrintToString(type) + "_" + newFactory(security)->toCString();
490 }
491
Yifan Hong1deca4b2021-09-10 16:16:44 -0700492 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
493 uint64_t length = str.length();
494 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
495 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
496 }
497
498 static inline std::string readString(android::base::borrowed_fd fd) {
499 uint64_t length;
500 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
501 std::string ret(length, '\0');
502 CHECK(android::base::ReadFully(fd, ret.data(), length));
503 return ret;
504 }
505
506 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
507 Parcel parcel;
508 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
509 writeString(fd,
510 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
511 }
512
513 template <typename T>
514 static inline T readFromFd(android::base::borrowed_fd fd) {
515 std::string data = readString(fd);
516 Parcel parcel;
517 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
518 T object;
519 CHECK_EQ(OK, object.readFromParcel(&parcel));
520 return object;
521 }
522
Steven Morelandc1635952021-04-01 16:20:47 +0000523 // This creates a new process serving an interface on a certain number of
524 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
527 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000528
Yifan Hong702115c2021-06-24 15:39:18 -0700529 SocketType socketType = std::get<0>(GetParam());
530 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000531
Steven Morelandda573042021-06-12 01:13:45 +0000532 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000533 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000534
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000535 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700536 .host = Process([&](android::base::borrowed_fd writeEnd,
537 android::base::borrowed_fd readEnd) {
538 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
539 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000540
541 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000542 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000543
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000544 unsigned int outPort = 0;
545
Steven Morelandc1635952021-04-01 16:20:47 +0000546 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700547 case SocketType::PRECONNECTED:
548 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000549 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000551 break;
552 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000554 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700555 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700556 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700557 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700558 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700559 }
Steven Morelandc1635952021-04-01 16:20:47 +0000560 default:
561 LOG_ALWAYS_FATAL("Unknown socket type");
562 }
563
Yifan Hong1deca4b2021-09-10 16:16:44 -0700564 BinderRpcTestServerInfo serverInfo;
565 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700566 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700567 writeToFd(writeEnd, serverInfo);
568 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
569
570 if (rpcSecurity == RpcSecurity::TLS) {
571 for (const auto& clientCert : clientInfo.certs) {
572 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700573 certVerifier
574 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
575 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700576 }
577 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000578
Steven Moreland611d15f2021-05-01 01:28:27 +0000579 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000580
Steven Morelandf137de92021-04-24 01:54:26 +0000581 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000582
583 // Another thread calls shutdown. Wait for it to complete.
584 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000585 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000586 };
587
Yifan Hong1deca4b2021-09-10 16:16:44 -0700588 std::vector<sp<RpcSession>> sessions;
589 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
590 for (size_t i = 0; i < options.numSessions; i++) {
591 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
592 }
593
594 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
595 BinderRpcTestClientInfo clientInfo;
596 for (const auto& session : sessions) {
597 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700598 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700599 }
600 writeToFd(ret.host.writeEnd(), clientInfo);
601
602 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700603 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700604 CHECK_NE(0, serverInfo.port);
605 }
606
607 if (rpcSecurity == RpcSecurity::TLS) {
608 const auto& serverCert = serverInfo.cert.data;
609 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700610 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
611 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700612 }
613
Steven Moreland2372f9d2021-08-05 15:42:01 -0700614 status_t status;
615
Yifan Hong1deca4b2021-09-10 16:16:44 -0700616 for (const auto& session : sessions) {
Yifan Hong10423062021-10-08 16:26:32 -0700617 session->setMaxIncomingThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000618
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000619 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700620 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700621 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700622 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700623 });
Steven Moreland4198a122021-08-03 17:37:58 -0700624 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000625 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700626 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000627 break;
628 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700629 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000630 break;
631 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700632 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000633 break;
634 default:
635 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000636 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700637 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000638 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000639 }
Steven Morelandc1635952021-04-01 16:20:47 +0000640 return ret;
641 }
642
Steven Moreland4313d7e2021-07-15 23:41:22 +0000643 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000644 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000645 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000646 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000647 sp<MyBinderRpcTest> service =
648 new MyBinderRpcTest;
649 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000650 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000651 }),
652 };
653
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000654 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000655 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
656
657 return ret;
658 }
659};
660
Steven Morelandc1635952021-04-01 16:20:47 +0000661TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000663 ASSERT_NE(proc.rootBinder, nullptr);
664 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
665}
666
Steven Moreland4cf688f2021-03-31 01:48:58 +0000667TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000668 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000669 ASSERT_NE(proc.rootBinder, nullptr);
670 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
671}
672
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000673TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000674 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000675 for (auto session : proc.proc.sessions) {
676 ASSERT_NE(nullptr, session.root);
677 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000678 }
679}
680
Steven Morelandc1635952021-04-01 16:20:47 +0000681TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000682 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000683 Parcel data;
684 Parcel reply;
685 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
686}
687
Steven Moreland67753c32021-04-02 18:45:19 +0000688TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000689 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000690
691 Parcel p1;
692 p1.markForBinder(proc.rootBinder);
693 p1.writeInt32(3);
694
695 Parcel p2;
696
697 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
698 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
699}
700
Steven Morelandc1635952021-04-01 16:20:47 +0000701TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000702 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000703 Parcel data;
704 data.markForBinder(proc.rootBinder);
705 Parcel reply;
706 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
707}
708
Steven Morelandc1635952021-04-01 16:20:47 +0000709TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000710 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000711 EXPECT_OK(proc.rootIface->sendString("asdf"));
712}
713
Steven Morelandc1635952021-04-01 16:20:47 +0000714TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000715 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000716 std::string doubled;
717 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
718 EXPECT_EQ("cool cool ", doubled);
719}
720
Steven Morelandc1635952021-04-01 16:20:47 +0000721TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000722 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000723 std::string single = std::string(1024, 'a');
724 std::string doubled;
725 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
726 EXPECT_EQ(single + single, doubled);
727}
728
Steven Morelandc1635952021-04-01 16:20:47 +0000729TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000730 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000731
732 int32_t pingResult;
733 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
734 EXPECT_EQ(OK, pingResult);
735
736 EXPECT_EQ(0, MyBinderRpcSession::gNum);
737}
738
Steven Morelandc1635952021-04-01 16:20:47 +0000739TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000740 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000741
742 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
743 sp<IBinder> outBinder;
744 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
745 EXPECT_EQ(inBinder, outBinder);
746
747 wp<IBinder> weak = inBinder;
748 inBinder = nullptr;
749 outBinder = nullptr;
750
751 // Force reading a reply, to process any pending dec refs from the other
752 // process (the other process will process dec refs there before processing
753 // the ping here).
754 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
755
756 EXPECT_EQ(nullptr, weak.promote());
757
758 EXPECT_EQ(0, MyBinderRpcSession::gNum);
759}
760
Steven Morelandc1635952021-04-01 16:20:47 +0000761TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000762 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000763
764 sp<IBinderRpcSession> session;
765 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
766
767 sp<IBinder> inBinder = IInterface::asBinder(session);
768 sp<IBinder> outBinder;
769 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
770 EXPECT_EQ(inBinder, outBinder);
771
772 wp<IBinder> weak = inBinder;
773 session = nullptr;
774 inBinder = nullptr;
775 outBinder = nullptr;
776
777 // Force reading a reply, to process any pending dec refs from the other
778 // process (the other process will process dec refs there before processing
779 // the ping here).
780 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
781
782 EXPECT_EQ(nullptr, weak.promote());
783}
784
Steven Morelandc1635952021-04-01 16:20:47 +0000785TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000786 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000787
788 sp<IBinder> outBinder;
789 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
790 EXPECT_EQ(nullptr, outBinder);
791}
792
Steven Morelandc1635952021-04-01 16:20:47 +0000793TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000794 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000795
796 IBinder* ptr = nullptr;
797 {
798 sp<IBinder> binder = new BBinder();
799 ptr = binder.get();
800 EXPECT_OK(proc.rootIface->holdBinder(binder));
801 }
802
803 sp<IBinder> held;
804 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
805
806 EXPECT_EQ(held.get(), ptr);
807
808 // stop holding binder, because we test to make sure references are cleaned
809 // up
810 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
811 // and flush ref counts
812 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
813}
814
815// START TESTS FOR LIMITATIONS OF SOCKET BINDER
816// These are behavioral differences form regular binder, where certain usecases
817// aren't supported.
818
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000819TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000820 auto proc1 = createRpcTestSocketServerProcess({});
821 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000822
823 sp<IBinder> outBinder;
824 EXPECT_EQ(INVALID_OPERATION,
825 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
826}
827
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000828TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000829 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000830
831 sp<IBinder> outBinder;
832 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000833 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000834 .transactionError());
835}
836
Steven Morelandc1635952021-04-01 16:20:47 +0000837TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000838 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000839
840 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
841 sp<IBinder> outBinder;
842 EXPECT_EQ(INVALID_OPERATION,
843 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
844}
845
Steven Morelandc1635952021-04-01 16:20:47 +0000846TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000847 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000848
849 // for historical reasons, IServiceManager interface only returns the
850 // exception code
851 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
852 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
853}
854
855// END TESTS FOR LIMITATIONS OF SOCKET BINDER
856
Steven Morelandc1635952021-04-01 16:20:47 +0000857TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000858 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000859
860 sp<IBinder> outBinder;
861 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
862 EXPECT_EQ(proc.rootBinder, outBinder);
863}
864
Steven Morelandc1635952021-04-01 16:20:47 +0000865TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000866 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000867
868 auto nastyNester = sp<MyBinderRpcTest>::make();
869 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
870
871 wp<IBinder> weak = nastyNester;
872 nastyNester = nullptr;
873 EXPECT_EQ(nullptr, weak.promote());
874}
875
Steven Morelandc1635952021-04-01 16:20:47 +0000876TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000877 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000878
879 sp<IBinder> a;
880 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
881
882 sp<IBinder> b;
883 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
884
885 EXPECT_EQ(a, b);
886}
887
Steven Morelandc1635952021-04-01 16:20:47 +0000888TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000889 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000890
891 sp<IBinder> a;
892 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
893 wp<IBinder> weak = a;
894 a = nullptr;
895
896 sp<IBinder> b;
897 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
898
899 // this is the wrong behavior, since BpBinder
900 // doesn't implement onIncStrongAttempted
901 // but make sure there is no crash
902 EXPECT_EQ(nullptr, weak.promote());
903
904 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
905
906 // In order to fix this:
907 // - need to have incStrongAttempted reflected across IPC boundary (wait for
908 // response to promote - round trip...)
909 // - sendOnLastWeakRef, to delete entries out of RpcState table
910 EXPECT_EQ(b, weak.promote());
911}
912
913#define expectSessions(expected, iface) \
914 do { \
915 int session; \
916 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
917 EXPECT_EQ(expected, session); \
918 } while (false)
919
Steven Morelandc1635952021-04-01 16:20:47 +0000920TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000921 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000922
923 sp<IBinderRpcSession> session;
924 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
925 std::string out;
926 EXPECT_OK(session->getName(&out));
927 EXPECT_EQ("aoeu", out);
928
929 expectSessions(1, proc.rootIface);
930 session = nullptr;
931 expectSessions(0, proc.rootIface);
932}
933
Steven Morelandc1635952021-04-01 16:20:47 +0000934TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000935 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000936
937 std::vector<sp<IBinderRpcSession>> sessions;
938
939 for (size_t i = 0; i < 15; i++) {
940 expectSessions(i, proc.rootIface);
941 sp<IBinderRpcSession> session;
942 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
943 sessions.push_back(session);
944 }
945 expectSessions(sessions.size(), proc.rootIface);
946 for (size_t i = 0; i < sessions.size(); i++) {
947 std::string out;
948 EXPECT_OK(sessions.at(i)->getName(&out));
949 EXPECT_EQ(std::to_string(i), out);
950 }
951 expectSessions(sessions.size(), proc.rootIface);
952
953 while (!sessions.empty()) {
954 sessions.pop_back();
955 expectSessions(sessions.size(), proc.rootIface);
956 }
957 expectSessions(0, proc.rootIface);
958}
959
960size_t epochMillis() {
961 using std::chrono::duration_cast;
962 using std::chrono::milliseconds;
963 using std::chrono::seconds;
964 using std::chrono::system_clock;
965 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
966}
967
Steven Morelandc1635952021-04-01 16:20:47 +0000968TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000969 constexpr size_t kNumThreads = 10;
970
Steven Moreland4313d7e2021-07-15 23:41:22 +0000971 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000972
973 EXPECT_OK(proc.rootIface->lock());
974
975 // block all but one thread taking locks
976 std::vector<std::thread> ts;
977 for (size_t i = 0; i < kNumThreads - 1; i++) {
978 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
979 }
980
981 usleep(100000); // give chance for calls on other threads
982
983 // other calls still work
984 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
985
986 constexpr size_t blockTimeMs = 500;
987 size_t epochMsBefore = epochMillis();
988 // after this, we should never see a response within this time
989 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
990
991 // this call should be blocked for blockTimeMs
992 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
993
994 size_t epochMsAfter = epochMillis();
995 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
996
997 for (auto& t : ts) t.join();
998}
999
Steven Morelandc1635952021-04-01 16:20:47 +00001000TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001001 constexpr size_t kNumThreads = 10;
1002 constexpr size_t kNumCalls = kNumThreads + 3;
1003 constexpr size_t kSleepMs = 500;
1004
Steven Moreland4313d7e2021-07-15 23:41:22 +00001005 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001006
1007 size_t epochMsBefore = epochMillis();
1008
1009 std::vector<std::thread> ts;
1010 for (size_t i = 0; i < kNumCalls; i++) {
1011 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
1012 }
1013
1014 for (auto& t : ts) t.join();
1015
1016 size_t epochMsAfter = epochMillis();
1017
1018 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
1019
1020 // Potential flake, but make sure calls are handled in parallel.
1021 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
1022}
1023
Steven Morelandc1635952021-04-01 16:20:47 +00001024TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001025 constexpr size_t kNumClientThreads = 10;
1026 constexpr size_t kNumServerThreads = 10;
1027 constexpr size_t kNumCalls = 100;
1028
Steven Moreland4313d7e2021-07-15 23:41:22 +00001029 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001030
1031 std::vector<std::thread> threads;
1032 for (size_t i = 0; i < kNumClientThreads; i++) {
1033 threads.push_back(std::thread([&] {
1034 for (size_t j = 0; j < kNumCalls; j++) {
1035 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001036 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001037 EXPECT_EQ(proc.rootBinder, out);
1038 }
1039 }));
1040 }
1041
1042 for (auto& t : threads) t.join();
1043}
1044
Steven Moreland925ba0a2021-09-17 18:06:32 -07001045static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1046 std::vector<std::thread> threads;
1047 for (size_t i = 0; i < threadCount; i++) {
1048 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1049 }
1050 for (auto& t : threads) t.join();
1051}
1052
Steven Morelandc6046982021-04-20 00:49:42 +00001053TEST_P(BinderRpc, OnewayStressTest) {
1054 constexpr size_t kNumClientThreads = 10;
1055 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001056 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001057
Steven Moreland4313d7e2021-07-15 23:41:22 +00001058 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001059
1060 std::vector<std::thread> threads;
1061 for (size_t i = 0; i < kNumClientThreads; i++) {
1062 threads.push_back(std::thread([&] {
1063 for (size_t j = 0; j < kNumCalls; j++) {
1064 EXPECT_OK(proc.rootIface->sendString("a"));
1065 }
Steven Morelandc6046982021-04-20 00:49:42 +00001066 }));
1067 }
1068
1069 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001070
1071 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001072}
1073
Steven Morelandc1635952021-04-01 16:20:47 +00001074TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001075 constexpr size_t kReallyLongTimeMs = 100;
1076 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1077
Steven Moreland4313d7e2021-07-15 23:41:22 +00001078 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001079
1080 size_t epochMsBefore = epochMillis();
1081
1082 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1083
1084 size_t epochMsAfter = epochMillis();
1085 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1086}
1087
Steven Morelandc1635952021-04-01 16:20:47 +00001088TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001089 constexpr size_t kNumSleeps = 10;
1090 constexpr size_t kNumExtraServerThreads = 4;
1091 constexpr size_t kSleepMs = 50;
1092
1093 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001094 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001095
1096 EXPECT_OK(proc.rootIface->lock());
1097
Steven Moreland1c678802021-09-17 16:48:47 -07001098 size_t epochMsBefore = epochMillis();
1099
1100 // all these *Async commands should be queued on the server sequentially,
1101 // even though there are multiple threads.
1102 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001103 proc.rootIface->sleepMsAsync(kSleepMs);
1104 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001105 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1106
Steven Moreland1c678802021-09-17 16:48:47 -07001107 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001108 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001109
Steven Moreland5553ac42020-11-11 02:14:45 +00001110 size_t epochMsAfter = epochMillis();
1111
1112 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001113
Steven Moreland925ba0a2021-09-17 18:06:32 -07001114 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001115}
1116
Steven Morelandd45be622021-06-04 02:19:37 +00001117TEST_P(BinderRpc, OnewayCallExhaustion) {
1118 constexpr size_t kNumClients = 2;
1119 constexpr size_t kTooLongMs = 1000;
1120
Steven Moreland4313d7e2021-07-15 23:41:22 +00001121 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001122
1123 // Build up oneway calls on the second session to make sure it terminates
1124 // and shuts down. The first session should be unaffected (proc destructor
1125 // checks the first session).
1126 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1127
1128 std::vector<std::thread> threads;
1129 for (size_t i = 0; i < kNumClients; i++) {
1130 // one of these threads will get stuck queueing a transaction once the
1131 // socket fills up, the other will be able to fill up transactions on
1132 // this object
1133 threads.push_back(std::thread([&] {
1134 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1135 }
1136 }));
1137 }
1138 for (auto& t : threads) t.join();
1139
1140 Status status = iface->sleepMsAsync(kTooLongMs);
1141 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1142
Steven Moreland798e0d12021-07-14 23:19:25 +00001143 // now that it has died, wait for the remote session to shutdown
1144 std::vector<int32_t> remoteCounts;
1145 do {
1146 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1147 } while (remoteCounts.size() == kNumClients);
1148
Steven Morelandd45be622021-06-04 02:19:37 +00001149 // the second session should be shutdown in the other process by the time we
1150 // are able to join above (it'll only be hung up once it finishes processing
1151 // any pending commands). We need to erase this session from the record
1152 // here, so that the destructor for our session won't check that this
1153 // session is valid, but we still want it to test the other session.
1154 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1155}
1156
Steven Moreland659416d2021-05-11 00:47:50 +00001157TEST_P(BinderRpc, Callbacks) {
1158 const static std::string kTestString = "good afternoon!";
1159
Steven Morelandc7d40132021-06-10 03:42:11 +00001160 for (bool callIsOneway : {true, false}) {
1161 for (bool callbackIsOneway : {true, false}) {
1162 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001163 auto proc = createRpcTestSocketServerProcess(
1164 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001165 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001166
Steven Morelandc7d40132021-06-10 03:42:11 +00001167 if (callIsOneway) {
1168 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1169 kTestString));
1170 } else {
1171 EXPECT_OK(
1172 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1173 }
Steven Moreland659416d2021-05-11 00:47:50 +00001174
Steven Morelandc7d40132021-06-10 03:42:11 +00001175 using std::literals::chrono_literals::operator""s;
1176 std::unique_lock<std::mutex> _l(cb->mMutex);
1177 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001178
Steven Morelandc7d40132021-06-10 03:42:11 +00001179 EXPECT_EQ(cb->mValues.size(), 1)
1180 << "callIsOneway: " << callIsOneway
1181 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1182 if (cb->mValues.empty()) continue;
1183 EXPECT_EQ(cb->mValues.at(0), kTestString)
1184 << "callIsOneway: " << callIsOneway
1185 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001186
Steven Morelandc7d40132021-06-10 03:42:11 +00001187 // since we are severing the connection, we need to go ahead and
1188 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001189 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1190 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1191 }
Steven Moreland659416d2021-05-11 00:47:50 +00001192
Steven Moreland1b304292021-07-15 22:59:34 +00001193 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001194 // need to manually shut it down
1195 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001196
Steven Morelandc7d40132021-06-10 03:42:11 +00001197 proc.expectAlreadyShutdown = true;
1198 }
Steven Moreland659416d2021-05-11 00:47:50 +00001199 }
1200 }
1201}
1202
Steven Moreland195edb82021-06-08 02:44:39 +00001203TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001204 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001205 auto cb = sp<MyBinderRpcCallback>::make();
1206
1207 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1208 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1209}
1210
Steven Morelandc1635952021-04-01 16:20:47 +00001211TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001212 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001213 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001214
1215 // make sure there is some state during crash
1216 // 1. we hold their binder
1217 sp<IBinderRpcSession> session;
1218 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1219 // 2. they hold our binder
1220 sp<IBinder> binder = new BBinder();
1221 EXPECT_OK(proc.rootIface->holdBinder(binder));
1222
1223 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1224 << "Do death cleanup: " << doDeathCleanup;
1225
Steven Morelandaf4ca712021-05-24 23:22:08 +00001226 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001227 }
1228}
1229
Steven Morelandd7302072021-05-15 01:32:04 +00001230TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001231 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001232
1233 // we can't allocate IPCThreadState so actually the first time should
1234 // succeed :(
1235 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1236
1237 // second time! we catch the error :)
1238 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1239
Steven Morelandaf4ca712021-05-24 23:22:08 +00001240 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001241}
1242
Steven Moreland37aff182021-03-26 02:04:16 +00001243TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001244 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001245
1246 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1247 ASSERT_NE(binder, nullptr);
1248
1249 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1250}
1251
1252TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001253 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001254
1255 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1256 ASSERT_NE(binder, nullptr);
1257
1258 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1259 ASSERT_NE(ndkBinder, nullptr);
1260
1261 std::string out;
1262 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1263 ASSERT_TRUE(status.isOk()) << status.getDescription();
1264 ASSERT_EQ("aoeuaoeu", out);
1265}
1266
Steven Moreland5553ac42020-11-11 02:14:45 +00001267ssize_t countFds() {
1268 DIR* dir = opendir("/proc/self/fd/");
1269 if (dir == nullptr) return -1;
1270 ssize_t ret = 0;
1271 dirent* ent;
1272 while ((ent = readdir(dir)) != nullptr) ret++;
1273 closedir(dir);
1274 return ret;
1275}
1276
Steven Morelandc1635952021-04-01 16:20:47 +00001277TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001278 ssize_t beforeFds = countFds();
1279 ASSERT_GE(beforeFds, 0);
1280 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001281 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001282 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1283 }
1284 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1285}
1286
Steven Morelandda573042021-06-12 01:13:45 +00001287static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001288 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001289 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001290 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001291 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001292 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1293 if (status == -EAFNOSUPPORT) {
1294 return false;
1295 }
1296 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1297 }
Steven Morelandda573042021-06-12 01:13:45 +00001298 server->start();
1299
Yifan Hongfdd9f692021-09-09 15:12:52 -07001300 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001301 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001302 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001303 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1304 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001305}
1306
Yifan Hong1deca4b2021-09-10 16:16:44 -07001307static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1308 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1309
1310 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001311
1312 static bool hasVsockLoopback = testSupportVsockLoopback();
1313
1314 if (hasVsockLoopback) {
1315 ret.push_back(SocketType::VSOCK);
1316 }
1317
1318 return ret;
1319}
1320
Yifan Hong702115c2021-06-24 15:39:18 -07001321INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1322 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1323 ::testing::ValuesIn(RpcSecurityValues())),
1324 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001325
Yifan Hong702115c2021-06-24 15:39:18 -07001326class BinderRpcServerRootObject
1327 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001328
1329TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1330 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1331 auto setRootObject = [](bool isStrong) -> SetFn {
1332 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1333 };
1334
Yifan Hong702115c2021-06-24 15:39:18 -07001335 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1336 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001337 auto binder1 = sp<BBinder>::make();
1338 IBinder* binderRaw1 = binder1.get();
1339 setRootObject(isStrong1)(server.get(), binder1);
1340 EXPECT_EQ(binderRaw1, server->getRootObject());
1341 binder1.clear();
1342 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1343
1344 auto binder2 = sp<BBinder>::make();
1345 IBinder* binderRaw2 = binder2.get();
1346 setRootObject(isStrong2)(server.get(), binder2);
1347 EXPECT_EQ(binderRaw2, server->getRootObject());
1348 binder2.clear();
1349 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1350}
1351
1352INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001353 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1354 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001355
Yifan Hong1a235852021-05-13 16:07:47 -07001356class OneOffSignal {
1357public:
1358 // If notify() was previously called, or is called within |duration|, return true; else false.
1359 template <typename R, typename P>
1360 bool wait(std::chrono::duration<R, P> duration) {
1361 std::unique_lock<std::mutex> lock(mMutex);
1362 return mCv.wait_for(lock, duration, [this] { return mValue; });
1363 }
1364 void notify() {
1365 std::unique_lock<std::mutex> lock(mMutex);
1366 mValue = true;
1367 lock.unlock();
1368 mCv.notify_all();
1369 }
1370
1371private:
1372 std::mutex mMutex;
1373 std::condition_variable mCv;
1374 bool mValue = false;
1375};
1376
Yifan Hong702115c2021-06-24 15:39:18 -07001377TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001378 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001379 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001380 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001381 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001382 auto joinEnds = std::make_shared<OneOffSignal>();
1383
1384 // If things are broken and the thread never stops, don't block other tests. Because the thread
1385 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1386 // shared pointers are passed.
1387 std::thread([server, joinEnds] {
1388 server->join();
1389 joinEnds->notify();
1390 }).detach();
1391
1392 bool shutdown = false;
1393 for (int i = 0; i < 10 && !shutdown; i++) {
1394 usleep(300 * 1000); // 300ms; total 3s
1395 if (server->shutdown()) shutdown = true;
1396 }
1397 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1398
1399 ASSERT_TRUE(joinEnds->wait(2s))
1400 << "After server->shutdown() returns true, join() did not stop after 2s";
1401}
1402
Yifan Hong194acf22021-06-29 18:44:56 -07001403TEST(BinderRpc, Java) {
1404#if !defined(__ANDROID__)
1405 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1406 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1407 "to binderHostDeviceTest. Hence, just disable this test on host.";
1408#endif // !__ANDROID__
1409 sp<IServiceManager> sm = defaultServiceManager();
1410 ASSERT_NE(nullptr, sm);
1411 // Any Java service with non-empty getInterfaceDescriptor() would do.
1412 // Let's pick batteryproperties.
1413 auto binder = sm->checkService(String16("batteryproperties"));
1414 ASSERT_NE(nullptr, binder);
1415 auto descriptor = binder->getInterfaceDescriptor();
1416 ASSERT_GE(descriptor.size(), 0);
1417 ASSERT_EQ(OK, binder->pingBinder());
1418
1419 auto rpcServer = RpcServer::make();
1420 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1421 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001422 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001423 auto socket = rpcServer->releaseServer();
1424
1425 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001426 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1427
1428 if (!android::base::GetBoolProperty("ro.debuggable", false)) {
1429 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
1430 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable builds, "
1431 "but get "
1432 << statusToString(setRpcClientDebugStatus);
1433 GTEST_SKIP();
1434 }
1435
1436 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001437
1438 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001439 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001440 auto rpcBinder = rpcSession->getRootObject();
1441 ASSERT_NE(nullptr, rpcBinder);
1442
1443 ASSERT_EQ(OK, rpcBinder->pingBinder());
1444
1445 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1446 << "getInterfaceDescriptor should not crash system_server";
1447 ASSERT_EQ(OK, rpcBinder->pingBinder());
1448}
1449
Yifan Hong702115c2021-06-24 15:39:18 -07001450INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1451 BinderRpcSimple::PrintTestParam);
1452
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001453class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001454public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001455 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001456 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001457
1458 // A server that handles client socket connections.
1459 class Server {
1460 public:
1461 explicit Server() {}
1462 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001463 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001464 [[nodiscard]] AssertionResult setUp(
1465 const Param& param,
1466 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1467 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001468 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1469 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1470 switch (socketType) {
1471 case SocketType::PRECONNECTED: {
1472 return AssertionFailure() << "Not supported by this test";
1473 } break;
1474 case SocketType::UNIX: {
1475 auto addr = allocateSocketAddress();
1476 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1477 if (status != OK) {
1478 return AssertionFailure()
1479 << "setupUnixDomainServer: " << statusToString(status);
1480 }
1481 mConnectToServer = [addr] {
1482 return connectTo(UnixSocketAddress(addr.c_str()));
1483 };
1484 } break;
1485 case SocketType::VSOCK: {
1486 auto port = allocateVsockPort();
1487 auto status = rpcServer->setupVsockServer(port);
1488 if (status != OK) {
1489 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1490 }
1491 mConnectToServer = [port] {
1492 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1493 };
1494 } break;
1495 case SocketType::INET: {
1496 unsigned int port;
1497 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1498 if (status != OK) {
1499 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1500 }
1501 mConnectToServer = [port] {
1502 const char* addr = kLocalInetAddress;
1503 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1504 if (aiStart == nullptr) return base::unique_fd{};
1505 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1506 auto fd = connectTo(
1507 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1508 if (fd.ok()) return fd;
1509 }
1510 ALOGE("None of the socket address resolved for %s:%u can be connected",
1511 addr, port);
1512 return base::unique_fd{};
1513 };
1514 }
1515 }
1516 mFd = rpcServer->releaseServer();
1517 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001518 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001519 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1520 mSetup = true;
1521 return AssertionSuccess();
1522 }
1523 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1524 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1525 return mCertVerifier;
1526 }
1527 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1528 void start() {
1529 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1530 mThread = std::make_unique<std::thread>(&Server::run, this);
1531 }
1532 void run() {
1533 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1534
1535 std::vector<std::thread> threads;
1536 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1537 base::unique_fd acceptedFd(
1538 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1539 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1540 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1541 }
1542
1543 for (auto& thread : threads) thread.join();
1544 }
1545 void handleOne(android::base::unique_fd acceptedFd) {
1546 ASSERT_TRUE(acceptedFd.ok());
1547 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1548 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001549 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001550 }
Yifan Honge07d2732021-09-13 21:59:14 -07001551 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001552 shutdown();
1553 join();
1554 }
1555 void shutdown() { mFdTrigger->trigger(); }
1556
1557 void setPostConnect(
1558 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1559 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001560 }
1561
1562 private:
1563 std::unique_ptr<std::thread> mThread;
1564 ConnectToServer mConnectToServer;
1565 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1566 base::unique_fd mFd;
1567 std::unique_ptr<RpcTransportCtx> mCtx;
1568 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1569 std::make_shared<RpcCertificateVerifierSimple>();
1570 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001571 // The function invoked after connection and handshake. By default, it is
1572 // |defaultPostConnect| that sends |kMessage| to the client.
1573 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1574 Server::defaultPostConnect;
1575
1576 void join() {
1577 if (mThread != nullptr) {
1578 mThread->join();
1579 mThread = nullptr;
1580 }
1581 }
1582
1583 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1584 FdTrigger* fdTrigger) {
1585 std::string message(kMessage);
1586 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001587 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001588 if (status != OK) return AssertionFailure() << statusToString(status);
1589 return AssertionSuccess();
1590 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001591 };
1592
1593 class Client {
1594 public:
1595 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1596 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001597 [[nodiscard]] AssertionResult setUp(const Param& param) {
1598 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001599 mFdTrigger = FdTrigger::make();
1600 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1601 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1602 return AssertionSuccess();
1603 }
1604 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1605 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1606 return mCertVerifier;
1607 }
Yifan Hong67519322021-09-13 18:51:16 -07001608 // connect() and do handshake
1609 bool setUpTransport() {
1610 mFd = mConnectToServer();
1611 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1612 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1613 return mClientTransport != nullptr;
1614 }
1615 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1616 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1617 std::string readMessage(expectedMessage.size(), '\0');
1618 status_t readStatus =
1619 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001620 readMessage.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001621 if (readStatus != OK) {
1622 return AssertionFailure() << statusToString(readStatus);
1623 }
1624 if (readMessage != expectedMessage) {
1625 return AssertionFailure()
1626 << "Expected " << expectedMessage << ", actual " << readMessage;
1627 }
1628 return AssertionSuccess();
1629 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001631 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001632 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1633 return;
1634 }
1635 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001636 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637 }
1638
1639 private:
1640 ConnectToServer mConnectToServer;
1641 base::unique_fd mFd;
1642 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1643 std::unique_ptr<RpcTransportCtx> mCtx;
1644 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1645 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001646 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001647 };
1648
1649 // Make A trust B.
1650 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001651 static status_t trust(RpcSecurity rpcSecurity,
1652 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1653 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001654 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001655 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1656 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1657 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001658 }
1659
1660 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001661};
1662
1663class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1664public:
1665 using Server = RpcTransportTestUtils::Server;
1666 using Client = RpcTransportTestUtils::Client;
1667 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1668 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1669 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1670 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1671 return ret;
1672 }
1673 static std::vector<ParamType> getRpcTranportTestParams() {
1674 std::vector<ParamType> ret;
1675 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1676 for (auto rpcSecurity : RpcSecurityValues()) {
1677 switch (rpcSecurity) {
1678 case RpcSecurity::RAW: {
1679 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1680 } break;
1681 case RpcSecurity::TLS: {
1682 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1683 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1684 } break;
1685 }
1686 }
1687 }
1688 return ret;
1689 }
1690 template <typename A, typename B>
1691 status_t trust(const A& a, const B& b) {
1692 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1693 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1694 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001695};
1696
1697TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001698 auto server = std::make_unique<Server>();
1699 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001700
1701 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001702 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001703
1704 ASSERT_EQ(OK, trust(&client, server));
1705 ASSERT_EQ(OK, trust(server, &client));
1706
1707 server->start();
1708 client.run();
1709}
1710
1711TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001712 auto server = std::make_unique<Server>();
1713 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001714
1715 std::vector<Client> clients;
1716 for (int i = 0; i < 2; i++) {
1717 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001718 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719 ASSERT_EQ(OK, trust(&client, server));
1720 ASSERT_EQ(OK, trust(server, &client));
1721 }
1722
1723 server->start();
1724 for (auto& client : clients) client.run();
1725}
1726
1727TEST_P(RpcTransportTest, UntrustedServer) {
1728 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1729
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001730 auto untrustedServer = std::make_unique<Server>();
1731 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001732
1733 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001734 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735
1736 ASSERT_EQ(OK, trust(untrustedServer, &client));
1737
1738 untrustedServer->start();
1739
1740 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1741 // the client can't verify the server's identity.
1742 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1743 client.run(handshakeOk);
1744}
1745TEST_P(RpcTransportTest, MaliciousServer) {
1746 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001747 auto validServer = std::make_unique<Server>();
1748 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001749
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001750 auto maliciousServer = std::make_unique<Server>();
1751 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001752
1753 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001754 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001755
1756 ASSERT_EQ(OK, trust(&client, validServer));
1757 ASSERT_EQ(OK, trust(validServer, &client));
1758 ASSERT_EQ(OK, trust(maliciousServer, &client));
1759
1760 maliciousServer->start();
1761
1762 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1763 // the client can't verify the server's identity.
1764 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1765 client.run(handshakeOk);
1766}
1767
1768TEST_P(RpcTransportTest, UntrustedClient) {
1769 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001770 auto server = std::make_unique<Server>();
1771 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001772
1773 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001774 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001775
1776 ASSERT_EQ(OK, trust(&client, server));
1777
1778 server->start();
1779
1780 // For TLS, Client should be able to verify server's identity, so client should see
1781 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1782 // identity and should drop the connection, so client shouldn't be able to read anything.
1783 bool readOk = rpcSecurity != RpcSecurity::TLS;
1784 client.run(true, readOk);
1785}
1786
1787TEST_P(RpcTransportTest, MaliciousClient) {
1788 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001789 auto server = std::make_unique<Server>();
1790 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791
1792 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001793 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001795 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001796
1797 ASSERT_EQ(OK, trust(&validClient, server));
1798 ASSERT_EQ(OK, trust(&maliciousClient, server));
1799
1800 server->start();
1801
1802 // See UntrustedClient.
1803 bool readOk = rpcSecurity != RpcSecurity::TLS;
1804 maliciousClient.run(true, readOk);
1805}
1806
Yifan Hong67519322021-09-13 18:51:16 -07001807TEST_P(RpcTransportTest, Trigger) {
1808 std::string msg2 = ", world!";
1809 std::mutex writeMutex;
1810 std::condition_variable writeCv;
1811 bool shouldContinueWriting = false;
1812 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001813 std::string message(RpcTransportTestUtils::kMessage);
Steven Moreland43921d52021-09-27 17:15:56 -07001814 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1815 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001816 if (status != OK) return AssertionFailure() << statusToString(status);
1817
1818 {
1819 std::unique_lock<std::mutex> lock(writeMutex);
1820 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1821 return AssertionFailure() << "write barrier not cleared in time!";
1822 }
1823 }
1824
Steven Moreland43921d52021-09-27 17:15:56 -07001825 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size(), {});
Steven Morelandc591b472021-09-16 13:56:11 -07001826 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001827 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001828 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001829 << statusToString(status);
1830 return AssertionSuccess();
1831 };
1832
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001833 auto server = std::make_unique<Server>();
1834 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001835
1836 // Set up client
1837 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001838 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001839
1840 // Exchange keys
1841 ASSERT_EQ(OK, trust(&client, server));
1842 ASSERT_EQ(OK, trust(server, &client));
1843
1844 server->setPostConnect(serverPostConnect);
1845
Yifan Hong67519322021-09-13 18:51:16 -07001846 server->start();
1847 // connect() to server and do handshake
1848 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001849 // read the first message. This ensures that server has finished handshake and start handling
1850 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001851 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001852 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1853 // write is on an FdTrigger that has been shut down.
1854 server->shutdown();
1855 // Continues server thread to write the second message.
1856 {
Yifan Hong22211f82021-09-14 12:32:25 -07001857 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001858 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001859 }
Yifan Hong22211f82021-09-14 12:32:25 -07001860 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001861 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001862 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001863 // On the client side, second read fails with DEAD_OBJECT
1864 ASSERT_FALSE(client.readMessage(msg2));
1865}
1866
Yifan Hong1deca4b2021-09-10 16:16:44 -07001867INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001868 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869 RpcTransportTest::PrintParamInfo);
1870
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001871class RpcTransportTlsKeyTest
1872 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1873public:
1874 template <typename A, typename B>
1875 status_t trust(const A& a, const B& b) {
1876 auto [socketType, certificateFormat, keyFormat] = GetParam();
1877 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1878 }
1879 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1880 auto [socketType, certificateFormat, keyFormat] = info.param;
1881 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1882 "_key_" + PrintToString(keyFormat);
1883 return ret;
1884 };
1885};
1886
1887TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1888 auto [socketType, certificateFormat, keyFormat] = GetParam();
1889
1890 std::vector<uint8_t> pkeyData, certData;
1891 {
1892 auto pkey = makeKeyPairForSelfSignedCert();
1893 ASSERT_NE(nullptr, pkey);
1894 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1895 ASSERT_NE(nullptr, cert);
1896 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1897 certData = serializeCertificate(cert.get(), certificateFormat);
1898 }
1899
1900 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1901 auto desCert = deserializeCertificate(certData, certificateFormat);
1902 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1903 auto utilsParam =
1904 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1905
1906 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1907 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1908
1909 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1910 ASSERT_TRUE(client.setUp(utilsParam));
1911
1912 ASSERT_EQ(OK, trust(&client, server));
1913 ASSERT_EQ(OK, trust(server, &client));
1914
1915 server->start();
1916 client.run();
1917}
1918
1919INSTANTIATE_TEST_CASE_P(
1920 BinderRpc, RpcTransportTlsKeyTest,
1921 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1922 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
1923 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
1924 RpcTransportTlsKeyTest::PrintParamInfo);
1925
Steven Morelandc1635952021-04-01 16:20:47 +00001926} // namespace android
1927
1928int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001929 ::testing::InitGoogleTest(&argc, argv);
1930 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1931 return RUN_ALL_TESTS();
1932}