1 /*
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
17 #include <BinderRpcTestClientInfo.h>
18 #include <BinderRpcTestServerInfo.h>
19 #include <BnBinderRpcCallback.h>
20 #include <BnBinderRpcSession.h>
21 #include <BnBinderRpcTest.h>
22 #include <aidl/IBinderRpcTest.h>
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/properties.h>
26 #include <android/binder_auto_utils.h>
27 #include <android/binder_libbinder.h>
28 #include <binder/Binder.h>
29 #include <binder/BpBinder.h>
30 #include <binder/IPCThreadState.h>
31 #include <binder/IServiceManager.h>
32 #include <binder/ProcessState.h>
33 #include <binder/RpcServer.h>
34 #include <binder/RpcSession.h>
35 #include <binder/RpcTlsTestUtils.h>
36 #include <binder/RpcTlsUtils.h>
37 #include <binder/RpcTransport.h>
38 #include <binder/RpcTransportRaw.h>
39 #include <binder/RpcTransportTls.h>
40 #include <gtest/gtest.h>
41
42 #include <chrono>
43 #include <cstdlib>
44 #include <iostream>
45 #include <thread>
46 #include <type_traits>
47
48 #include <poll.h>
49 #include <sys/prctl.h>
50 #include <unistd.h>
51
52 #include "../FdTrigger.h"
53 #include "../RpcSocketAddress.h" // for testing preconnected clients
54 #include "../RpcState.h" // for debugging
55 #include "../vm_sockets.h" // for VMADDR_*
56
57 using namespace std::chrono_literals;
58 using namespace std::placeholders;
59 using testing::AssertionFailure;
60 using testing::AssertionResult;
61 using testing::AssertionSuccess;
62
63 namespace android {
64
65 static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
66 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
67 const char* kLocalInetAddress = "127.0.0.1";
68
69 enum class RpcSecurity { RAW, TLS };
70
RpcSecurityValues()71 static inline std::vector<RpcSecurity> RpcSecurityValues() {
72 return {RpcSecurity::RAW, RpcSecurity::TLS};
73 }
74
newFactory(RpcSecurity rpcSecurity,std::shared_ptr<RpcCertificateVerifier> verifier=nullptr,std::unique_ptr<RpcAuth> auth=nullptr)75 static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
76 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
77 std::unique_ptr<RpcAuth> auth = nullptr) {
78 switch (rpcSecurity) {
79 case RpcSecurity::RAW:
80 return RpcTransportCtxFactoryRaw::make();
81 case RpcSecurity::TLS: {
82 if (verifier == nullptr) {
83 verifier = std::make_shared<RpcCertificateVerifierSimple>();
84 }
85 if (auth == nullptr) {
86 auth = std::make_unique<RpcAuthSelfSigned>();
87 }
88 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
89 }
90 default:
91 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
92 }
93 }
94
TEST(BinderRpcParcel,EntireParcelFormatted)95 TEST(BinderRpcParcel, EntireParcelFormatted) {
96 Parcel p;
97 p.writeInt32(3);
98
99 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
100 }
101
102 class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
103 public:
PrintTestParam(const::testing::TestParamInfo<ParamType> & info)104 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
105 return newFactory(info.param)->toCString();
106 }
107 };
108
TEST_P(BinderRpcSimple,SetExternalServerTest)109 TEST_P(BinderRpcSimple, SetExternalServerTest) {
110 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
111 int sinkFd = sink.get();
112 auto server = RpcServer::make(newFactory(GetParam()));
113 ASSERT_FALSE(server->hasServer());
114 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
115 ASSERT_TRUE(server->hasServer());
116 base::unique_fd retrieved = server->releaseServer();
117 ASSERT_FALSE(server->hasServer());
118 ASSERT_EQ(sinkFd, retrieved.get());
119 }
120
TEST(BinderRpc,CannotUseNextWireVersion)121 TEST(BinderRpc, CannotUseNextWireVersion) {
122 auto session = RpcSession::make();
123 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
124 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
125 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
126 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
127 }
128
TEST(BinderRpc,CanUseExperimentalWireVersion)129 TEST(BinderRpc, CanUseExperimentalWireVersion) {
130 auto session = RpcSession::make();
131 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
132 }
133
134 using android::binder::Status;
135
136 #define EXPECT_OK(status) \
137 do { \
138 Status stat = (status); \
139 EXPECT_TRUE(stat.isOk()) << stat; \
140 } while (false)
141
142 class MyBinderRpcSession : public BnBinderRpcSession {
143 public:
144 static std::atomic<int32_t> gNum;
145
MyBinderRpcSession(const std::string & name)146 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
getName(std::string * name)147 Status getName(std::string* name) override {
148 *name = mName;
149 return Status::ok();
150 }
~MyBinderRpcSession()151 ~MyBinderRpcSession() { gNum--; }
152
153 private:
154 std::string mName;
155 };
156 std::atomic<int32_t> MyBinderRpcSession::gNum;
157
158 class MyBinderRpcCallback : public BnBinderRpcCallback {
sendCallback(const std::string & value)159 Status sendCallback(const std::string& value) {
160 std::unique_lock _l(mMutex);
161 mValues.push_back(value);
162 _l.unlock();
163 mCv.notify_one();
164 return Status::ok();
165 }
sendOnewayCallback(const std::string & value)166 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
167
168 public:
169 std::mutex mMutex;
170 std::condition_variable mCv;
171 std::vector<std::string> mValues;
172 };
173
174 class MyBinderRpcTest : public BnBinderRpcTest {
175 public:
176 wp<RpcServer> server;
177 int port = 0;
178
sendString(const std::string & str)179 Status sendString(const std::string& str) override {
180 (void)str;
181 return Status::ok();
182 }
doubleString(const std::string & str,std::string * strstr)183 Status doubleString(const std::string& str, std::string* strstr) override {
184 *strstr = str + str;
185 return Status::ok();
186 }
getClientPort(int * out)187 Status getClientPort(int* out) override {
188 *out = port;
189 return Status::ok();
190 }
countBinders(std::vector<int32_t> * out)191 Status countBinders(std::vector<int32_t>* out) override {
192 sp<RpcServer> spServer = server.promote();
193 if (spServer == nullptr) {
194 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
195 }
196 out->clear();
197 for (auto session : spServer->listSessions()) {
198 size_t count = session->state()->countBinders();
199 out->push_back(count);
200 }
201 return Status::ok();
202 }
pingMe(const sp<IBinder> & binder,int32_t * out)203 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
204 if (binder == nullptr) {
205 std::cout << "Received null binder!" << std::endl;
206 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
207 }
208 *out = binder->pingBinder();
209 return Status::ok();
210 }
repeatBinder(const sp<IBinder> & binder,sp<IBinder> * out)211 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
212 *out = binder;
213 return Status::ok();
214 }
215 static sp<IBinder> mHeldBinder;
holdBinder(const sp<IBinder> & binder)216 Status holdBinder(const sp<IBinder>& binder) override {
217 mHeldBinder = binder;
218 return Status::ok();
219 }
getHeldBinder(sp<IBinder> * held)220 Status getHeldBinder(sp<IBinder>* held) override {
221 *held = mHeldBinder;
222 return Status::ok();
223 }
nestMe(const sp<IBinderRpcTest> & binder,int count)224 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
225 if (count <= 0) return Status::ok();
226 return binder->nestMe(this, count - 1);
227 }
alwaysGiveMeTheSameBinder(sp<IBinder> * out)228 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
229 static sp<IBinder> binder = new BBinder;
230 *out = binder;
231 return Status::ok();
232 }
openSession(const std::string & name,sp<IBinderRpcSession> * out)233 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
234 *out = new MyBinderRpcSession(name);
235 return Status::ok();
236 }
getNumOpenSessions(int32_t * out)237 Status getNumOpenSessions(int32_t* out) override {
238 *out = MyBinderRpcSession::gNum;
239 return Status::ok();
240 }
241
242 std::mutex blockMutex;
lock()243 Status lock() override {
244 blockMutex.lock();
245 return Status::ok();
246 }
unlockInMsAsync(int32_t ms)247 Status unlockInMsAsync(int32_t ms) override {
248 usleep(ms * 1000);
249 blockMutex.unlock();
250 return Status::ok();
251 }
lockUnlock()252 Status lockUnlock() override {
253 std::lock_guard<std::mutex> _l(blockMutex);
254 return Status::ok();
255 }
256
sleepMs(int32_t ms)257 Status sleepMs(int32_t ms) override {
258 usleep(ms * 1000);
259 return Status::ok();
260 }
261
sleepMsAsync(int32_t ms)262 Status sleepMsAsync(int32_t ms) override {
263 // In-process binder calls are asynchronous, but the call to this method
264 // is synchronous wrt its client. This in/out-process threading model
265 // diffentiation is a classic binder leaky abstraction (for better or
266 // worse) and is preserved here the way binder sockets plugs itself
267 // into BpBinder, as nothing is changed at the higher levels
268 // (IInterface) which result in this behavior.
269 return sleepMs(ms);
270 }
271
doCallback(const sp<IBinderRpcCallback> & callback,bool oneway,bool delayed,const std::string & value)272 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
273 const std::string& value) override {
274 if (callback == nullptr) {
275 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
276 }
277
278 if (delayed) {
279 std::thread([=]() {
280 ALOGE("Executing delayed callback: '%s'", value.c_str());
281 Status status = doCallback(callback, oneway, false, value);
282 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
283 }).detach();
284 return Status::ok();
285 }
286
287 if (oneway) {
288 return callback->sendOnewayCallback(value);
289 }
290
291 return callback->sendCallback(value);
292 }
293
doCallbackAsync(const sp<IBinderRpcCallback> & callback,bool oneway,bool delayed,const std::string & value)294 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
295 const std::string& value) override {
296 return doCallback(callback, oneway, delayed, value);
297 }
298
die(bool cleanup)299 Status die(bool cleanup) override {
300 if (cleanup) {
301 exit(1);
302 } else {
303 _exit(1);
304 }
305 }
306
scheduleShutdown()307 Status scheduleShutdown() override {
308 sp<RpcServer> strongServer = server.promote();
309 if (strongServer == nullptr) {
310 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
311 }
312 std::thread([=] {
313 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
314 }).detach();
315 return Status::ok();
316 }
317
useKernelBinderCallingId()318 Status useKernelBinderCallingId() override {
319 // this is WRONG! It does not make sense when using RPC binder, and
320 // because it is SO wrong, and so much code calls this, it should abort!
321
322 (void)IPCThreadState::self()->getCallingPid();
323 return Status::ok();
324 }
325 };
326 sp<IBinder> MyBinderRpcTest::mHeldBinder;
327
328 class Process {
329 public:
330 Process(Process&&) = default;
Process(const std::function<void (android::base::borrowed_fd,android::base::borrowed_fd)> & f)331 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
332 android::base::borrowed_fd /* readEnd */)>& f) {
333 android::base::unique_fd childWriteEnd;
334 android::base::unique_fd childReadEnd;
335 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
336 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
337 if (0 == (mPid = fork())) {
338 // racey: assume parent doesn't crash before this is set
339 prctl(PR_SET_PDEATHSIG, SIGHUP);
340
341 f(childWriteEnd, childReadEnd);
342
343 exit(0);
344 }
345 }
~Process()346 ~Process() {
347 if (mPid != 0) {
348 waitpid(mPid, nullptr, 0);
349 }
350 }
readEnd()351 android::base::borrowed_fd readEnd() { return mReadEnd; }
writeEnd()352 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
353
354 private:
355 pid_t mPid = 0;
356 android::base::unique_fd mReadEnd;
357 android::base::unique_fd mWriteEnd;
358 };
359
allocateSocketAddress()360 static std::string allocateSocketAddress() {
361 static size_t id = 0;
362 std::string temp = getenv("TMPDIR") ?: "/tmp";
363 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
364 unlink(ret.c_str());
365 return ret;
366 };
367
allocateVsockPort()368 static unsigned int allocateVsockPort() {
369 static unsigned int vsockPort = 3456;
370 return vsockPort++;
371 }
372
373 struct ProcessSession {
374 // reference to process hosting a socket server
375 Process host;
376
377 struct SessionInfo {
378 sp<RpcSession> session;
379 sp<IBinder> root;
380 };
381
382 // client session objects associated with other process
383 // each one represents a separate session
384 std::vector<SessionInfo> sessions;
385
386 ProcessSession(ProcessSession&&) = default;
~ProcessSessionandroid::ProcessSession387 ~ProcessSession() {
388 for (auto& session : sessions) {
389 session.root = nullptr;
390 }
391
392 for (auto& info : sessions) {
393 sp<RpcSession>& session = info.session;
394
395 EXPECT_NE(nullptr, session);
396 EXPECT_NE(nullptr, session->state());
397 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
398
399 wp<RpcSession> weakSession = session;
400 session = nullptr;
401 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
402 }
403 }
404 };
405
406 // Process session where the process hosts IBinderRpcTest, the server used
407 // for most testing here
408 struct BinderRpcTestProcessSession {
409 ProcessSession proc;
410
411 // pre-fetched root object (for first session)
412 sp<IBinder> rootBinder;
413
414 // pre-casted root object (for first session)
415 sp<IBinderRpcTest> rootIface;
416
417 // whether session should be invalidated by end of run
418 bool expectAlreadyShutdown = false;
419
420 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
~BinderRpcTestProcessSessionandroid::BinderRpcTestProcessSession421 ~BinderRpcTestProcessSession() {
422 EXPECT_NE(nullptr, rootIface);
423 if (rootIface == nullptr) return;
424
425 if (!expectAlreadyShutdown) {
426 std::vector<int32_t> remoteCounts;
427 // calling over any sessions counts across all sessions
428 EXPECT_OK(rootIface->countBinders(&remoteCounts));
429 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
430 for (auto remoteCount : remoteCounts) {
431 EXPECT_EQ(remoteCount, 1);
432 }
433
434 // even though it is on another thread, shutdown races with
435 // the transaction reply being written
436 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
437 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
438 }
439 }
440
441 rootIface = nullptr;
442 rootBinder = nullptr;
443 }
444 };
445
446 enum class SocketType {
447 PRECONNECTED,
448 UNIX,
449 VSOCK,
450 INET,
451 };
PrintToString(SocketType socketType)452 static inline std::string PrintToString(SocketType socketType) {
453 switch (socketType) {
454 case SocketType::PRECONNECTED:
455 return "preconnected_uds";
456 case SocketType::UNIX:
457 return "unix_domain_socket";
458 case SocketType::VSOCK:
459 return "vm_socket";
460 case SocketType::INET:
461 return "inet_socket";
462 default:
463 LOG_ALWAYS_FATAL("Unknown socket type");
464 return "";
465 }
466 }
467
connectTo(const RpcSocketAddress & addr)468 static base::unique_fd connectTo(const RpcSocketAddress& addr) {
469 base::unique_fd serverFd(
470 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
471 int savedErrno = errno;
472 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
473 << strerror(savedErrno);
474
475 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
476 int savedErrno = errno;
477 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
478 << strerror(savedErrno);
479 }
480 return serverFd;
481 }
482
483 class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
484 public:
485 struct Options {
486 size_t numThreads = 1;
487 size_t numSessions = 1;
488 size_t numIncomingConnections = 0;
489 size_t numOutgoingConnections = SIZE_MAX;
490 };
491
PrintParamInfo(const testing::TestParamInfo<ParamType> & info)492 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
493 auto [type, security] = info.param;
494 return PrintToString(type) + "_" + newFactory(security)->toCString();
495 }
496
writeString(android::base::borrowed_fd fd,std::string_view str)497 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
498 uint64_t length = str.length();
499 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
500 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
501 }
502
readString(android::base::borrowed_fd fd)503 static inline std::string readString(android::base::borrowed_fd fd) {
504 uint64_t length;
505 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
506 std::string ret(length, '\0');
507 CHECK(android::base::ReadFully(fd, ret.data(), length));
508 return ret;
509 }
510
writeToFd(android::base::borrowed_fd fd,const Parcelable & parcelable)511 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
512 Parcel parcel;
513 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
514 writeString(fd,
515 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
516 }
517
518 template <typename T>
readFromFd(android::base::borrowed_fd fd)519 static inline T readFromFd(android::base::borrowed_fd fd) {
520 std::string data = readString(fd);
521 Parcel parcel;
522 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
523 T object;
524 CHECK_EQ(OK, object.readFromParcel(&parcel));
525 return object;
526 }
527
528 // This creates a new process serving an interface on a certain number of
529 // threads.
createRpcTestSocketServerProcess(const Options & options,const std::function<void (const sp<RpcServer> &)> & configure)530 ProcessSession createRpcTestSocketServerProcess(
531 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
532 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
533
534 SocketType socketType = std::get<0>(GetParam());
535 RpcSecurity rpcSecurity = std::get<1>(GetParam());
536
537 unsigned int vsockPort = allocateVsockPort();
538 std::string addr = allocateSocketAddress();
539
540 auto ret = ProcessSession{
541 .host = Process([&](android::base::borrowed_fd writeEnd,
542 android::base::borrowed_fd readEnd) {
543 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
544 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
545
546 server->setMaxThreads(options.numThreads);
547
548 unsigned int outPort = 0;
549
550 switch (socketType) {
551 case SocketType::PRECONNECTED:
552 [[fallthrough]];
553 case SocketType::UNIX:
554 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
555 break;
556 case SocketType::VSOCK:
557 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
558 break;
559 case SocketType::INET: {
560 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
561 CHECK_NE(0, outPort);
562 break;
563 }
564 default:
565 LOG_ALWAYS_FATAL("Unknown socket type");
566 }
567
568 BinderRpcTestServerInfo serverInfo;
569 serverInfo.port = static_cast<int64_t>(outPort);
570 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
571 writeToFd(writeEnd, serverInfo);
572 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
573
574 if (rpcSecurity == RpcSecurity::TLS) {
575 for (const auto& clientCert : clientInfo.certs) {
576 CHECK_EQ(OK,
577 certVerifier
578 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
579 clientCert.data));
580 }
581 }
582
583 configure(server);
584
585 server->join();
586
587 // Another thread calls shutdown. Wait for it to complete.
588 (void)server->shutdown();
589 }),
590 };
591
592 std::vector<sp<RpcSession>> sessions;
593 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
594 for (size_t i = 0; i < options.numSessions; i++) {
595 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
596 }
597
598 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
599 BinderRpcTestClientInfo clientInfo;
600 for (const auto& session : sessions) {
601 auto& parcelableCert = clientInfo.certs.emplace_back();
602 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
603 }
604 writeToFd(ret.host.writeEnd(), clientInfo);
605
606 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
607 if (socketType == SocketType::INET) {
608 CHECK_NE(0, serverInfo.port);
609 }
610
611 if (rpcSecurity == RpcSecurity::TLS) {
612 const auto& serverCert = serverInfo.cert.data;
613 CHECK_EQ(OK,
614 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
615 serverCert));
616 }
617
618 status_t status;
619
620 for (const auto& session : sessions) {
621 session->setMaxIncomingThreads(options.numIncomingConnections);
622 session->setMaxOutgoingThreads(options.numOutgoingConnections);
623
624 switch (socketType) {
625 case SocketType::PRECONNECTED:
626 status = session->setupPreconnectedClient({}, [=]() {
627 return connectTo(UnixSocketAddress(addr.c_str()));
628 });
629 break;
630 case SocketType::UNIX:
631 status = session->setupUnixDomainClient(addr.c_str());
632 break;
633 case SocketType::VSOCK:
634 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
635 break;
636 case SocketType::INET:
637 status = session->setupInetClient("127.0.0.1", serverInfo.port);
638 break;
639 default:
640 LOG_ALWAYS_FATAL("Unknown socket type");
641 }
642 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
643 ret.sessions.push_back({session, session->getRootObject()});
644 }
645 return ret;
646 }
647
createRpcTestSocketServerProcess(const Options & options)648 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
649 BinderRpcTestProcessSession ret{
650 .proc = createRpcTestSocketServerProcess(
651 options,
652 [&](const sp<RpcServer>& server) {
653 server->setPerSessionRootObject([&](const sockaddr* addr,
654 socklen_t len) {
655 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
656 switch (addr->sa_family) {
657 case AF_UNIX:
658 // nothing to save
659 break;
660 case AF_VSOCK:
661 CHECK_EQ(len, sizeof(sockaddr_vm));
662 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
663 ->svm_port;
664 break;
665 case AF_INET:
666 CHECK_EQ(len, sizeof(sockaddr_in));
667 service->port =
668 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
669 ->sin_port);
670 break;
671 case AF_INET6:
672 CHECK_EQ(len, sizeof(sockaddr_in));
673 service->port =
674 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
675 ->sin6_port);
676 break;
677 default:
678 LOG_ALWAYS_FATAL("Unrecognized address family %d",
679 addr->sa_family);
680 }
681 service->server = server;
682 return service;
683 });
684 }),
685 };
686
687 ret.rootBinder = ret.proc.sessions.at(0).root;
688 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
689
690 return ret;
691 }
692
693 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
694 size_t sleepMs = 500);
695 };
696
TEST_P(BinderRpc,Ping)697 TEST_P(BinderRpc, Ping) {
698 auto proc = createRpcTestSocketServerProcess({});
699 ASSERT_NE(proc.rootBinder, nullptr);
700 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
701 }
702
TEST_P(BinderRpc,GetInterfaceDescriptor)703 TEST_P(BinderRpc, GetInterfaceDescriptor) {
704 auto proc = createRpcTestSocketServerProcess({});
705 ASSERT_NE(proc.rootBinder, nullptr);
706 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
707 }
708
TEST_P(BinderRpc,MultipleSessions)709 TEST_P(BinderRpc, MultipleSessions) {
710 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
711 for (auto session : proc.proc.sessions) {
712 ASSERT_NE(nullptr, session.root);
713 EXPECT_EQ(OK, session.root->pingBinder());
714 }
715 }
716
TEST_P(BinderRpc,SeparateRootObject)717 TEST_P(BinderRpc, SeparateRootObject) {
718 SocketType type = std::get<0>(GetParam());
719 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
720 // we can't get port numbers for unix sockets
721 return;
722 }
723
724 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
725
726 int port1 = 0;
727 EXPECT_OK(proc.rootIface->getClientPort(&port1));
728
729 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
730 int port2;
731 EXPECT_OK(rootIface2->getClientPort(&port2));
732
733 // we should have a different IBinderRpcTest object created for each
734 // session, because we use setPerSessionRootObject
735 EXPECT_NE(port1, port2);
736 }
737
TEST_P(BinderRpc,TransactionsMustBeMarkedRpc)738 TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
739 auto proc = createRpcTestSocketServerProcess({});
740 Parcel data;
741 Parcel reply;
742 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
743 }
744
TEST_P(BinderRpc,AppendSeparateFormats)745 TEST_P(BinderRpc, AppendSeparateFormats) {
746 auto proc1 = createRpcTestSocketServerProcess({});
747 auto proc2 = createRpcTestSocketServerProcess({});
748
749 Parcel pRaw;
750
751 Parcel p1;
752 p1.markForBinder(proc1.rootBinder);
753 p1.writeInt32(3);
754
755 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, p1.dataSize()));
756 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
757
758 Parcel p2;
759 p2.markForBinder(proc2.rootBinder);
760 p2.writeInt32(7);
761
762 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
763 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
764 }
765
TEST_P(BinderRpc,UnknownTransaction)766 TEST_P(BinderRpc, UnknownTransaction) {
767 auto proc = createRpcTestSocketServerProcess({});
768 Parcel data;
769 data.markForBinder(proc.rootBinder);
770 Parcel reply;
771 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
772 }
773
TEST_P(BinderRpc,SendSomethingOneway)774 TEST_P(BinderRpc, SendSomethingOneway) {
775 auto proc = createRpcTestSocketServerProcess({});
776 EXPECT_OK(proc.rootIface->sendString("asdf"));
777 }
778
TEST_P(BinderRpc,SendAndGetResultBack)779 TEST_P(BinderRpc, SendAndGetResultBack) {
780 auto proc = createRpcTestSocketServerProcess({});
781 std::string doubled;
782 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
783 EXPECT_EQ("cool cool ", doubled);
784 }
785
TEST_P(BinderRpc,SendAndGetResultBackBig)786 TEST_P(BinderRpc, SendAndGetResultBackBig) {
787 auto proc = createRpcTestSocketServerProcess({});
788 std::string single = std::string(1024, 'a');
789 std::string doubled;
790 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
791 EXPECT_EQ(single + single, doubled);
792 }
793
TEST_P(BinderRpc,CallMeBack)794 TEST_P(BinderRpc, CallMeBack) {
795 auto proc = createRpcTestSocketServerProcess({});
796
797 int32_t pingResult;
798 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
799 EXPECT_EQ(OK, pingResult);
800
801 EXPECT_EQ(0, MyBinderRpcSession::gNum);
802 }
803
TEST_P(BinderRpc,RepeatBinder)804 TEST_P(BinderRpc, RepeatBinder) {
805 auto proc = createRpcTestSocketServerProcess({});
806
807 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
808 sp<IBinder> outBinder;
809 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
810 EXPECT_EQ(inBinder, outBinder);
811
812 wp<IBinder> weak = inBinder;
813 inBinder = nullptr;
814 outBinder = nullptr;
815
816 // Force reading a reply, to process any pending dec refs from the other
817 // process (the other process will process dec refs there before processing
818 // the ping here).
819 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
820
821 EXPECT_EQ(nullptr, weak.promote());
822
823 EXPECT_EQ(0, MyBinderRpcSession::gNum);
824 }
825
TEST_P(BinderRpc,RepeatTheirBinder)826 TEST_P(BinderRpc, RepeatTheirBinder) {
827 auto proc = createRpcTestSocketServerProcess({});
828
829 sp<IBinderRpcSession> session;
830 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
831
832 sp<IBinder> inBinder = IInterface::asBinder(session);
833 sp<IBinder> outBinder;
834 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
835 EXPECT_EQ(inBinder, outBinder);
836
837 wp<IBinder> weak = inBinder;
838 session = nullptr;
839 inBinder = nullptr;
840 outBinder = nullptr;
841
842 // Force reading a reply, to process any pending dec refs from the other
843 // process (the other process will process dec refs there before processing
844 // the ping here).
845 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
846
847 EXPECT_EQ(nullptr, weak.promote());
848 }
849
TEST_P(BinderRpc,RepeatBinderNull)850 TEST_P(BinderRpc, RepeatBinderNull) {
851 auto proc = createRpcTestSocketServerProcess({});
852
853 sp<IBinder> outBinder;
854 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
855 EXPECT_EQ(nullptr, outBinder);
856 }
857
TEST_P(BinderRpc,HoldBinder)858 TEST_P(BinderRpc, HoldBinder) {
859 auto proc = createRpcTestSocketServerProcess({});
860
861 IBinder* ptr = nullptr;
862 {
863 sp<IBinder> binder = new BBinder();
864 ptr = binder.get();
865 EXPECT_OK(proc.rootIface->holdBinder(binder));
866 }
867
868 sp<IBinder> held;
869 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
870
871 EXPECT_EQ(held.get(), ptr);
872
873 // stop holding binder, because we test to make sure references are cleaned
874 // up
875 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
876 // and flush ref counts
877 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
878 }
879
880 // START TESTS FOR LIMITATIONS OF SOCKET BINDER
881 // These are behavioral differences form regular binder, where certain usecases
882 // aren't supported.
883
TEST_P(BinderRpc,CannotMixBindersBetweenUnrelatedSocketSessions)884 TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
885 auto proc1 = createRpcTestSocketServerProcess({});
886 auto proc2 = createRpcTestSocketServerProcess({});
887
888 sp<IBinder> outBinder;
889 EXPECT_EQ(INVALID_OPERATION,
890 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
891 }
892
TEST_P(BinderRpc,CannotMixBindersBetweenTwoSessionsToTheSameServer)893 TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
894 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
895
896 sp<IBinder> outBinder;
897 EXPECT_EQ(INVALID_OPERATION,
898 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
899 .transactionError());
900 }
901
TEST_P(BinderRpc,CannotSendRegularBinderOverSocketBinder)902 TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
903 auto proc = createRpcTestSocketServerProcess({});
904
905 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
906 sp<IBinder> outBinder;
907 EXPECT_EQ(INVALID_OPERATION,
908 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
909 }
910
TEST_P(BinderRpc,CannotSendSocketBinderOverRegularBinder)911 TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
912 auto proc = createRpcTestSocketServerProcess({});
913
914 // for historical reasons, IServiceManager interface only returns the
915 // exception code
916 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
917 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
918 }
919
920 // END TESTS FOR LIMITATIONS OF SOCKET BINDER
921
TEST_P(BinderRpc,RepeatRootObject)922 TEST_P(BinderRpc, RepeatRootObject) {
923 auto proc = createRpcTestSocketServerProcess({});
924
925 sp<IBinder> outBinder;
926 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
927 EXPECT_EQ(proc.rootBinder, outBinder);
928 }
929
TEST_P(BinderRpc,NestedTransactions)930 TEST_P(BinderRpc, NestedTransactions) {
931 auto proc = createRpcTestSocketServerProcess({});
932
933 auto nastyNester = sp<MyBinderRpcTest>::make();
934 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
935
936 wp<IBinder> weak = nastyNester;
937 nastyNester = nullptr;
938 EXPECT_EQ(nullptr, weak.promote());
939 }
940
TEST_P(BinderRpc,SameBinderEquality)941 TEST_P(BinderRpc, SameBinderEquality) {
942 auto proc = createRpcTestSocketServerProcess({});
943
944 sp<IBinder> a;
945 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
946
947 sp<IBinder> b;
948 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
949
950 EXPECT_EQ(a, b);
951 }
952
TEST_P(BinderRpc,SameBinderEqualityWeak)953 TEST_P(BinderRpc, SameBinderEqualityWeak) {
954 auto proc = createRpcTestSocketServerProcess({});
955
956 sp<IBinder> a;
957 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
958 wp<IBinder> weak = a;
959 a = nullptr;
960
961 sp<IBinder> b;
962 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
963
964 // this is the wrong behavior, since BpBinder
965 // doesn't implement onIncStrongAttempted
966 // but make sure there is no crash
967 EXPECT_EQ(nullptr, weak.promote());
968
969 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
970
971 // In order to fix this:
972 // - need to have incStrongAttempted reflected across IPC boundary (wait for
973 // response to promote - round trip...)
974 // - sendOnLastWeakRef, to delete entries out of RpcState table
975 EXPECT_EQ(b, weak.promote());
976 }
977
978 #define expectSessions(expected, iface) \
979 do { \
980 int session; \
981 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
982 EXPECT_EQ(expected, session); \
983 } while (false)
984
TEST_P(BinderRpc,SingleSession)985 TEST_P(BinderRpc, SingleSession) {
986 auto proc = createRpcTestSocketServerProcess({});
987
988 sp<IBinderRpcSession> session;
989 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
990 std::string out;
991 EXPECT_OK(session->getName(&out));
992 EXPECT_EQ("aoeu", out);
993
994 expectSessions(1, proc.rootIface);
995 session = nullptr;
996 expectSessions(0, proc.rootIface);
997 }
998
TEST_P(BinderRpc,ManySessions)999 TEST_P(BinderRpc, ManySessions) {
1000 auto proc = createRpcTestSocketServerProcess({});
1001
1002 std::vector<sp<IBinderRpcSession>> sessions;
1003
1004 for (size_t i = 0; i < 15; i++) {
1005 expectSessions(i, proc.rootIface);
1006 sp<IBinderRpcSession> session;
1007 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1008 sessions.push_back(session);
1009 }
1010 expectSessions(sessions.size(), proc.rootIface);
1011 for (size_t i = 0; i < sessions.size(); i++) {
1012 std::string out;
1013 EXPECT_OK(sessions.at(i)->getName(&out));
1014 EXPECT_EQ(std::to_string(i), out);
1015 }
1016 expectSessions(sessions.size(), proc.rootIface);
1017
1018 while (!sessions.empty()) {
1019 sessions.pop_back();
1020 expectSessions(sessions.size(), proc.rootIface);
1021 }
1022 expectSessions(0, proc.rootIface);
1023 }
1024
epochMillis()1025 size_t epochMillis() {
1026 using std::chrono::duration_cast;
1027 using std::chrono::milliseconds;
1028 using std::chrono::seconds;
1029 using std::chrono::system_clock;
1030 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1031 }
1032
TEST_P(BinderRpc,ThreadPoolGreaterThanEqualRequested)1033 TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
1034 constexpr size_t kNumThreads = 10;
1035
1036 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1037
1038 EXPECT_OK(proc.rootIface->lock());
1039
1040 // block all but one thread taking locks
1041 std::vector<std::thread> ts;
1042 for (size_t i = 0; i < kNumThreads - 1; i++) {
1043 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1044 }
1045
1046 usleep(100000); // give chance for calls on other threads
1047
1048 // other calls still work
1049 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1050
1051 constexpr size_t blockTimeMs = 500;
1052 size_t epochMsBefore = epochMillis();
1053 // after this, we should never see a response within this time
1054 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1055
1056 // this call should be blocked for blockTimeMs
1057 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1058
1059 size_t epochMsAfter = epochMillis();
1060 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1061
1062 for (auto& t : ts) t.join();
1063 }
1064
testThreadPoolOverSaturated(sp<IBinderRpcTest> iface,size_t numCalls,size_t sleepMs)1065 void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1066 size_t sleepMs) {
1067 size_t epochMsBefore = epochMillis();
1068
1069 std::vector<std::thread> ts;
1070 for (size_t i = 0; i < numCalls; i++) {
1071 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
1072 }
1073
1074 for (auto& t : ts) t.join();
1075
1076 size_t epochMsAfter = epochMillis();
1077
1078 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
1079
1080 // Potential flake, but make sure calls are handled in parallel.
1081 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1082 }
1083
TEST_P(BinderRpc,ThreadPoolOverSaturated)1084 TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1085 constexpr size_t kNumThreads = 10;
1086 constexpr size_t kNumCalls = kNumThreads + 3;
1087 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1088 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1089 }
1090
TEST_P(BinderRpc,ThreadPoolLimitOutgoing)1091 TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1092 constexpr size_t kNumThreads = 20;
1093 constexpr size_t kNumOutgoingConnections = 10;
1094 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1095 auto proc = createRpcTestSocketServerProcess(
1096 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1097 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1098 }
1099
TEST_P(BinderRpc,ThreadingStressTest)1100 TEST_P(BinderRpc, ThreadingStressTest) {
1101 constexpr size_t kNumClientThreads = 10;
1102 constexpr size_t kNumServerThreads = 10;
1103 constexpr size_t kNumCalls = 100;
1104
1105 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
1106
1107 std::vector<std::thread> threads;
1108 for (size_t i = 0; i < kNumClientThreads; i++) {
1109 threads.push_back(std::thread([&] {
1110 for (size_t j = 0; j < kNumCalls; j++) {
1111 sp<IBinder> out;
1112 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
1113 EXPECT_EQ(proc.rootBinder, out);
1114 }
1115 }));
1116 }
1117
1118 for (auto& t : threads) t.join();
1119 }
1120
saturateThreadPool(size_t threadCount,const sp<IBinderRpcTest> & iface)1121 static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1122 std::vector<std::thread> threads;
1123 for (size_t i = 0; i < threadCount; i++) {
1124 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1125 }
1126 for (auto& t : threads) t.join();
1127 }
1128
TEST_P(BinderRpc,OnewayStressTest)1129 TEST_P(BinderRpc, OnewayStressTest) {
1130 constexpr size_t kNumClientThreads = 10;
1131 constexpr size_t kNumServerThreads = 10;
1132 constexpr size_t kNumCalls = 1000;
1133
1134 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
1135
1136 std::vector<std::thread> threads;
1137 for (size_t i = 0; i < kNumClientThreads; i++) {
1138 threads.push_back(std::thread([&] {
1139 for (size_t j = 0; j < kNumCalls; j++) {
1140 EXPECT_OK(proc.rootIface->sendString("a"));
1141 }
1142 }));
1143 }
1144
1145 for (auto& t : threads) t.join();
1146
1147 saturateThreadPool(kNumServerThreads, proc.rootIface);
1148 }
1149
TEST_P(BinderRpc,OnewayCallDoesNotWait)1150 TEST_P(BinderRpc, OnewayCallDoesNotWait) {
1151 constexpr size_t kReallyLongTimeMs = 100;
1152 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1153
1154 auto proc = createRpcTestSocketServerProcess({});
1155
1156 size_t epochMsBefore = epochMillis();
1157
1158 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1159
1160 size_t epochMsAfter = epochMillis();
1161 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1162 }
1163
TEST_P(BinderRpc,OnewayCallQueueing)1164 TEST_P(BinderRpc, OnewayCallQueueing) {
1165 constexpr size_t kNumSleeps = 10;
1166 constexpr size_t kNumExtraServerThreads = 4;
1167 constexpr size_t kSleepMs = 50;
1168
1169 // make sure calls to the same object happen on the same thread
1170 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
1171
1172 EXPECT_OK(proc.rootIface->lock());
1173
1174 size_t epochMsBefore = epochMillis();
1175
1176 // all these *Async commands should be queued on the server sequentially,
1177 // even though there are multiple threads.
1178 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
1179 proc.rootIface->sleepMsAsync(kSleepMs);
1180 }
1181 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1182
1183 // this can only return once the final async call has unlocked
1184 EXPECT_OK(proc.rootIface->lockUnlock());
1185
1186 size_t epochMsAfter = epochMillis();
1187
1188 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
1189
1190 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
1191 }
1192
TEST_P(BinderRpc,OnewayCallExhaustion)1193 TEST_P(BinderRpc, OnewayCallExhaustion) {
1194 constexpr size_t kNumClients = 2;
1195 constexpr size_t kTooLongMs = 1000;
1196
1197 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
1198
1199 // Build up oneway calls on the second session to make sure it terminates
1200 // and shuts down. The first session should be unaffected (proc destructor
1201 // checks the first session).
1202 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1203
1204 std::vector<std::thread> threads;
1205 for (size_t i = 0; i < kNumClients; i++) {
1206 // one of these threads will get stuck queueing a transaction once the
1207 // socket fills up, the other will be able to fill up transactions on
1208 // this object
1209 threads.push_back(std::thread([&] {
1210 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1211 }
1212 }));
1213 }
1214 for (auto& t : threads) t.join();
1215
1216 Status status = iface->sleepMsAsync(kTooLongMs);
1217 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1218
1219 // now that it has died, wait for the remote session to shutdown
1220 std::vector<int32_t> remoteCounts;
1221 do {
1222 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1223 } while (remoteCounts.size() == kNumClients);
1224
1225 // the second session should be shutdown in the other process by the time we
1226 // are able to join above (it'll only be hung up once it finishes processing
1227 // any pending commands). We need to erase this session from the record
1228 // here, so that the destructor for our session won't check that this
1229 // session is valid, but we still want it to test the other session.
1230 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1231 }
1232
TEST_P(BinderRpc,Callbacks)1233 TEST_P(BinderRpc, Callbacks) {
1234 const static std::string kTestString = "good afternoon!";
1235
1236 for (bool callIsOneway : {true, false}) {
1237 for (bool callbackIsOneway : {true, false}) {
1238 for (bool delayed : {true, false}) {
1239 auto proc = createRpcTestSocketServerProcess(
1240 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1241 auto cb = sp<MyBinderRpcCallback>::make();
1242
1243 if (callIsOneway) {
1244 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1245 kTestString));
1246 } else {
1247 EXPECT_OK(
1248 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1249 }
1250
1251 using std::literals::chrono_literals::operator""s;
1252 std::unique_lock<std::mutex> _l(cb->mMutex);
1253 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1254
1255 EXPECT_EQ(cb->mValues.size(), 1)
1256 << "callIsOneway: " << callIsOneway
1257 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1258 if (cb->mValues.empty()) continue;
1259 EXPECT_EQ(cb->mValues.at(0), kTestString)
1260 << "callIsOneway: " << callIsOneway
1261 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1262
1263 // since we are severing the connection, we need to go ahead and
1264 // tell the server to shutdown and exit so that waitpid won't hang
1265 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1266 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1267 }
1268
1269 // since this session has an incoming connection w/ a threadpool, we
1270 // need to manually shut it down
1271 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1272
1273 proc.expectAlreadyShutdown = true;
1274 }
1275 }
1276 }
1277 }
1278
TEST_P(BinderRpc,OnewayCallbackWithNoThread)1279 TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1280 auto proc = createRpcTestSocketServerProcess({});
1281 auto cb = sp<MyBinderRpcCallback>::make();
1282
1283 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1284 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1285 }
1286
TEST_P(BinderRpc,Die)1287 TEST_P(BinderRpc, Die) {
1288 for (bool doDeathCleanup : {true, false}) {
1289 auto proc = createRpcTestSocketServerProcess({});
1290
1291 // make sure there is some state during crash
1292 // 1. we hold their binder
1293 sp<IBinderRpcSession> session;
1294 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1295 // 2. they hold our binder
1296 sp<IBinder> binder = new BBinder();
1297 EXPECT_OK(proc.rootIface->holdBinder(binder));
1298
1299 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1300 << "Do death cleanup: " << doDeathCleanup;
1301
1302 proc.expectAlreadyShutdown = true;
1303 }
1304 }
1305
TEST_P(BinderRpc,UseKernelBinderCallingId)1306 TEST_P(BinderRpc, UseKernelBinderCallingId) {
1307 bool okToFork = ProcessState::selfOrNull() == nullptr;
1308
1309 auto proc = createRpcTestSocketServerProcess({});
1310
1311 // If this process has used ProcessState already, then the forked process
1312 // cannot use it at all. If this process hasn't used it (depending on the
1313 // order tests are run), then the forked process can use it, and we'll only
1314 // catch the invalid usage the second time. Such is the burden of global
1315 // state!
1316 if (okToFork) {
1317 // we can't allocate IPCThreadState so actually the first time should
1318 // succeed :(
1319 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1320 }
1321
1322 // second time! we catch the error :)
1323 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1324
1325 proc.expectAlreadyShutdown = true;
1326 }
1327
TEST_P(BinderRpc,WorksWithLibbinderNdkPing)1328 TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1329 auto proc = createRpcTestSocketServerProcess({});
1330
1331 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1332 ASSERT_NE(binder, nullptr);
1333
1334 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1335 }
1336
TEST_P(BinderRpc,WorksWithLibbinderNdkUserTransaction)1337 TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1338 auto proc = createRpcTestSocketServerProcess({});
1339
1340 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1341 ASSERT_NE(binder, nullptr);
1342
1343 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1344 ASSERT_NE(ndkBinder, nullptr);
1345
1346 std::string out;
1347 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1348 ASSERT_TRUE(status.isOk()) << status.getDescription();
1349 ASSERT_EQ("aoeuaoeu", out);
1350 }
1351
countFds()1352 ssize_t countFds() {
1353 DIR* dir = opendir("/proc/self/fd/");
1354 if (dir == nullptr) return -1;
1355 ssize_t ret = 0;
1356 dirent* ent;
1357 while ((ent = readdir(dir)) != nullptr) ret++;
1358 closedir(dir);
1359 return ret;
1360 }
1361
TEST_P(BinderRpc,Fds)1362 TEST_P(BinderRpc, Fds) {
1363 ssize_t beforeFds = countFds();
1364 ASSERT_GE(beforeFds, 0);
1365 {
1366 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
1367 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1368 }
1369 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1370 }
1371
TEST_P(BinderRpc,AidlDelegatorTest)1372 TEST_P(BinderRpc, AidlDelegatorTest) {
1373 auto proc = createRpcTestSocketServerProcess({});
1374 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1375 ASSERT_NE(nullptr, myDelegator);
1376
1377 std::string doubled;
1378 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1379 EXPECT_EQ("cool cool ", doubled);
1380 }
1381
testSupportVsockLoopback()1382 static bool testSupportVsockLoopback() {
1383 // We don't need to enable TLS to know if vsock is supported.
1384 unsigned int vsockPort = allocateVsockPort();
1385 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
1386 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1387 if (status == -EAFNOSUPPORT) {
1388 return false;
1389 }
1390 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1391 }
1392 server->start();
1393
1394 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
1395 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
1396 while (!server->shutdown()) usleep(10000);
1397 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1398 return status == OK;
1399 }
1400
testSocketTypes(bool hasPreconnected=true)1401 static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1402 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1403
1404 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
1405
1406 static bool hasVsockLoopback = testSupportVsockLoopback();
1407
1408 if (hasVsockLoopback) {
1409 ret.push_back(SocketType::VSOCK);
1410 }
1411
1412 return ret;
1413 }
1414
1415 INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1416 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1417 ::testing::ValuesIn(RpcSecurityValues())),
1418 BinderRpc::PrintParamInfo);
1419
1420 class BinderRpcServerRootObject
1421 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
1422
TEST_P(BinderRpcServerRootObject,WeakRootObject)1423 TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1424 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1425 auto setRootObject = [](bool isStrong) -> SetFn {
1426 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1427 };
1428
1429 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1430 auto server = RpcServer::make(newFactory(rpcSecurity));
1431 auto binder1 = sp<BBinder>::make();
1432 IBinder* binderRaw1 = binder1.get();
1433 setRootObject(isStrong1)(server.get(), binder1);
1434 EXPECT_EQ(binderRaw1, server->getRootObject());
1435 binder1.clear();
1436 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1437
1438 auto binder2 = sp<BBinder>::make();
1439 IBinder* binderRaw2 = binder2.get();
1440 setRootObject(isStrong2)(server.get(), binder2);
1441 EXPECT_EQ(binderRaw2, server->getRootObject());
1442 binder2.clear();
1443 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1444 }
1445
1446 INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1447 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1448 ::testing::ValuesIn(RpcSecurityValues())));
1449
1450 class OneOffSignal {
1451 public:
1452 // If notify() was previously called, or is called within |duration|, return true; else false.
1453 template <typename R, typename P>
wait(std::chrono::duration<R,P> duration)1454 bool wait(std::chrono::duration<R, P> duration) {
1455 std::unique_lock<std::mutex> lock(mMutex);
1456 return mCv.wait_for(lock, duration, [this] { return mValue; });
1457 }
notify()1458 void notify() {
1459 std::unique_lock<std::mutex> lock(mMutex);
1460 mValue = true;
1461 lock.unlock();
1462 mCv.notify_all();
1463 }
1464
1465 private:
1466 std::mutex mMutex;
1467 std::condition_variable mCv;
1468 bool mValue = false;
1469 };
1470
TEST_P(BinderRpcSimple,Shutdown)1471 TEST_P(BinderRpcSimple, Shutdown) {
1472 auto addr = allocateSocketAddress();
1473 auto server = RpcServer::make(newFactory(GetParam()));
1474 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1475 auto joinEnds = std::make_shared<OneOffSignal>();
1476
1477 // If things are broken and the thread never stops, don't block other tests. Because the thread
1478 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1479 // shared pointers are passed.
1480 std::thread([server, joinEnds] {
1481 server->join();
1482 joinEnds->notify();
1483 }).detach();
1484
1485 bool shutdown = false;
1486 for (int i = 0; i < 10 && !shutdown; i++) {
1487 usleep(300 * 1000); // 300ms; total 3s
1488 if (server->shutdown()) shutdown = true;
1489 }
1490 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1491
1492 ASSERT_TRUE(joinEnds->wait(2s))
1493 << "After server->shutdown() returns true, join() did not stop after 2s";
1494 }
1495
TEST(BinderRpc,Java)1496 TEST(BinderRpc, Java) {
1497 #if !defined(__ANDROID__)
1498 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1499 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1500 "to binderHostDeviceTest. Hence, just disable this test on host.";
1501 #endif // !__ANDROID__
1502 sp<IServiceManager> sm = defaultServiceManager();
1503 ASSERT_NE(nullptr, sm);
1504 // Any Java service with non-empty getInterfaceDescriptor() would do.
1505 // Let's pick batteryproperties.
1506 auto binder = sm->checkService(String16("batteryproperties"));
1507 ASSERT_NE(nullptr, binder);
1508 auto descriptor = binder->getInterfaceDescriptor();
1509 ASSERT_GE(descriptor.size(), 0);
1510 ASSERT_EQ(OK, binder->pingBinder());
1511
1512 auto rpcServer = RpcServer::make();
1513 unsigned int port;
1514 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
1515 auto socket = rpcServer->releaseServer();
1516
1517 auto keepAlive = sp<BBinder>::make();
1518 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1519
1520 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1521 android::base::GetProperty("ro.build.type", "") == "user") {
1522 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
1523 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1524 "builds, but get "
1525 << statusToString(setRpcClientDebugStatus);
1526 GTEST_SKIP();
1527 }
1528
1529 ASSERT_EQ(OK, setRpcClientDebugStatus);
1530
1531 auto rpcSession = RpcSession::make();
1532 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
1533 auto rpcBinder = rpcSession->getRootObject();
1534 ASSERT_NE(nullptr, rpcBinder);
1535
1536 ASSERT_EQ(OK, rpcBinder->pingBinder());
1537
1538 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1539 << "getInterfaceDescriptor should not crash system_server";
1540 ASSERT_EQ(OK, rpcBinder->pingBinder());
1541 }
1542
1543 INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1544 BinderRpcSimple::PrintTestParam);
1545
1546 class RpcTransportTestUtils {
1547 public:
1548 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
1549 using ConnectToServer = std::function<base::unique_fd()>;
1550
1551 // A server that handles client socket connections.
1552 class Server {
1553 public:
Server()1554 explicit Server() {}
1555 Server(Server&&) = default;
~Server()1556 ~Server() { shutdownAndWait(); }
setUp(const Param & param,std::unique_ptr<RpcAuth> auth=std::make_unique<RpcAuthSelfSigned> ())1557 [[nodiscard]] AssertionResult setUp(
1558 const Param& param,
1559 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1560 auto [socketType, rpcSecurity, certificateFormat] = param;
1561 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1562 switch (socketType) {
1563 case SocketType::PRECONNECTED: {
1564 return AssertionFailure() << "Not supported by this test";
1565 } break;
1566 case SocketType::UNIX: {
1567 auto addr = allocateSocketAddress();
1568 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1569 if (status != OK) {
1570 return AssertionFailure()
1571 << "setupUnixDomainServer: " << statusToString(status);
1572 }
1573 mConnectToServer = [addr] {
1574 return connectTo(UnixSocketAddress(addr.c_str()));
1575 };
1576 } break;
1577 case SocketType::VSOCK: {
1578 auto port = allocateVsockPort();
1579 auto status = rpcServer->setupVsockServer(port);
1580 if (status != OK) {
1581 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1582 }
1583 mConnectToServer = [port] {
1584 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1585 };
1586 } break;
1587 case SocketType::INET: {
1588 unsigned int port;
1589 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1590 if (status != OK) {
1591 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1592 }
1593 mConnectToServer = [port] {
1594 const char* addr = kLocalInetAddress;
1595 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1596 if (aiStart == nullptr) return base::unique_fd{};
1597 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1598 auto fd = connectTo(
1599 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1600 if (fd.ok()) return fd;
1601 }
1602 ALOGE("None of the socket address resolved for %s:%u can be connected",
1603 addr, port);
1604 return base::unique_fd{};
1605 };
1606 }
1607 }
1608 mFd = rpcServer->releaseServer();
1609 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
1610 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
1611 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1612 mSetup = true;
1613 return AssertionSuccess();
1614 }
getCtx() const1615 RpcTransportCtx* getCtx() const { return mCtx.get(); }
getCertVerifier() const1616 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1617 return mCertVerifier;
1618 }
getConnectToServerFn()1619 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
start()1620 void start() {
1621 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1622 mThread = std::make_unique<std::thread>(&Server::run, this);
1623 }
run()1624 void run() {
1625 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1626
1627 std::vector<std::thread> threads;
1628 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1629 base::unique_fd acceptedFd(
1630 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1631 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1632 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1633 }
1634
1635 for (auto& thread : threads) thread.join();
1636 }
handleOne(android::base::unique_fd acceptedFd)1637 void handleOne(android::base::unique_fd acceptedFd) {
1638 ASSERT_TRUE(acceptedFd.ok());
1639 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1640 if (serverTransport == nullptr) return; // handshake failed
1641 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
1642 }
shutdownAndWait()1643 void shutdownAndWait() {
1644 shutdown();
1645 join();
1646 }
shutdown()1647 void shutdown() { mFdTrigger->trigger(); }
1648
setPostConnect(std::function<AssertionResult (RpcTransport *,FdTrigger * fdTrigger)> fn)1649 void setPostConnect(
1650 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1651 mPostConnect = std::move(fn);
1652 }
1653
1654 private:
1655 std::unique_ptr<std::thread> mThread;
1656 ConnectToServer mConnectToServer;
1657 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1658 base::unique_fd mFd;
1659 std::unique_ptr<RpcTransportCtx> mCtx;
1660 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1661 std::make_shared<RpcCertificateVerifierSimple>();
1662 bool mSetup = false;
1663 // The function invoked after connection and handshake. By default, it is
1664 // |defaultPostConnect| that sends |kMessage| to the client.
1665 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1666 Server::defaultPostConnect;
1667
join()1668 void join() {
1669 if (mThread != nullptr) {
1670 mThread->join();
1671 mThread = nullptr;
1672 }
1673 }
1674
defaultPostConnect(RpcTransport * serverTransport,FdTrigger * fdTrigger)1675 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1676 FdTrigger* fdTrigger) {
1677 std::string message(kMessage);
1678 iovec messageIov{message.data(), message.size()};
1679 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, {});
1680 if (status != OK) return AssertionFailure() << statusToString(status);
1681 return AssertionSuccess();
1682 }
1683 };
1684
1685 class Client {
1686 public:
Client(ConnectToServer connectToServer)1687 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1688 Client(Client&&) = default;
setUp(const Param & param)1689 [[nodiscard]] AssertionResult setUp(const Param& param) {
1690 auto [socketType, rpcSecurity, certificateFormat] = param;
1691 mFdTrigger = FdTrigger::make();
1692 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1693 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1694 return AssertionSuccess();
1695 }
getCtx() const1696 RpcTransportCtx* getCtx() const { return mCtx.get(); }
getCertVerifier() const1697 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1698 return mCertVerifier;
1699 }
1700 // connect() and do handshake
setUpTransport()1701 bool setUpTransport() {
1702 mFd = mConnectToServer();
1703 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1704 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1705 return mClientTransport != nullptr;
1706 }
readMessage(const std::string & expectedMessage=kMessage)1707 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1708 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1709 std::string readMessage(expectedMessage.size(), '\0');
1710 iovec readMessageIov{readMessage.data(), readMessage.size()};
1711 status_t readStatus = mClientTransport->interruptableReadFully(mFdTrigger.get(),
1712 &readMessageIov, 1, {});
1713 if (readStatus != OK) {
1714 return AssertionFailure() << statusToString(readStatus);
1715 }
1716 if (readMessage != expectedMessage) {
1717 return AssertionFailure()
1718 << "Expected " << expectedMessage << ", actual " << readMessage;
1719 }
1720 return AssertionSuccess();
1721 }
run(bool handshakeOk=true,bool readOk=true)1722 void run(bool handshakeOk = true, bool readOk = true) {
1723 if (!setUpTransport()) {
1724 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1725 return;
1726 }
1727 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
1728 ASSERT_EQ(readOk, readMessage());
1729 }
1730
1731 private:
1732 ConnectToServer mConnectToServer;
1733 base::unique_fd mFd;
1734 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1735 std::unique_ptr<RpcTransportCtx> mCtx;
1736 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1737 std::make_shared<RpcCertificateVerifierSimple>();
1738 std::unique_ptr<RpcTransport> mClientTransport;
1739 };
1740
1741 // Make A trust B.
1742 template <typename A, typename B>
trust(RpcSecurity rpcSecurity,std::optional<RpcCertificateFormat> certificateFormat,const A & a,const B & b)1743 static status_t trust(RpcSecurity rpcSecurity,
1744 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1745 const B& b) {
1746 if (rpcSecurity != RpcSecurity::TLS) return OK;
1747 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1748 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1749 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
1750 }
1751
1752 static constexpr const char* kMessage = "hello";
1753 };
1754
1755 class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1756 public:
1757 using Server = RpcTransportTestUtils::Server;
1758 using Client = RpcTransportTestUtils::Client;
PrintParamInfo(const testing::TestParamInfo<ParamType> & info)1759 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1760 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1761 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1762 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1763 return ret;
1764 }
getRpcTranportTestParams()1765 static std::vector<ParamType> getRpcTranportTestParams() {
1766 std::vector<ParamType> ret;
1767 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1768 for (auto rpcSecurity : RpcSecurityValues()) {
1769 switch (rpcSecurity) {
1770 case RpcSecurity::RAW: {
1771 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1772 } break;
1773 case RpcSecurity::TLS: {
1774 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1775 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1776 } break;
1777 }
1778 }
1779 }
1780 return ret;
1781 }
1782 template <typename A, typename B>
trust(const A & a,const B & b)1783 status_t trust(const A& a, const B& b) {
1784 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1785 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1786 }
1787 };
1788
TEST_P(RpcTransportTest,GoodCertificate)1789 TEST_P(RpcTransportTest, GoodCertificate) {
1790 auto server = std::make_unique<Server>();
1791 ASSERT_TRUE(server->setUp(GetParam()));
1792
1793 Client client(server->getConnectToServerFn());
1794 ASSERT_TRUE(client.setUp(GetParam()));
1795
1796 ASSERT_EQ(OK, trust(&client, server));
1797 ASSERT_EQ(OK, trust(server, &client));
1798
1799 server->start();
1800 client.run();
1801 }
1802
TEST_P(RpcTransportTest,MultipleClients)1803 TEST_P(RpcTransportTest, MultipleClients) {
1804 auto server = std::make_unique<Server>();
1805 ASSERT_TRUE(server->setUp(GetParam()));
1806
1807 std::vector<Client> clients;
1808 for (int i = 0; i < 2; i++) {
1809 auto& client = clients.emplace_back(server->getConnectToServerFn());
1810 ASSERT_TRUE(client.setUp(GetParam()));
1811 ASSERT_EQ(OK, trust(&client, server));
1812 ASSERT_EQ(OK, trust(server, &client));
1813 }
1814
1815 server->start();
1816 for (auto& client : clients) client.run();
1817 }
1818
TEST_P(RpcTransportTest,UntrustedServer)1819 TEST_P(RpcTransportTest, UntrustedServer) {
1820 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1821
1822 auto untrustedServer = std::make_unique<Server>();
1823 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
1824
1825 Client client(untrustedServer->getConnectToServerFn());
1826 ASSERT_TRUE(client.setUp(GetParam()));
1827
1828 ASSERT_EQ(OK, trust(untrustedServer, &client));
1829
1830 untrustedServer->start();
1831
1832 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1833 // the client can't verify the server's identity.
1834 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1835 client.run(handshakeOk);
1836 }
TEST_P(RpcTransportTest,MaliciousServer)1837 TEST_P(RpcTransportTest, MaliciousServer) {
1838 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1839 auto validServer = std::make_unique<Server>();
1840 ASSERT_TRUE(validServer->setUp(GetParam()));
1841
1842 auto maliciousServer = std::make_unique<Server>();
1843 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
1844
1845 Client client(maliciousServer->getConnectToServerFn());
1846 ASSERT_TRUE(client.setUp(GetParam()));
1847
1848 ASSERT_EQ(OK, trust(&client, validServer));
1849 ASSERT_EQ(OK, trust(validServer, &client));
1850 ASSERT_EQ(OK, trust(maliciousServer, &client));
1851
1852 maliciousServer->start();
1853
1854 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1855 // the client can't verify the server's identity.
1856 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1857 client.run(handshakeOk);
1858 }
1859
TEST_P(RpcTransportTest,UntrustedClient)1860 TEST_P(RpcTransportTest, UntrustedClient) {
1861 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1862 auto server = std::make_unique<Server>();
1863 ASSERT_TRUE(server->setUp(GetParam()));
1864
1865 Client client(server->getConnectToServerFn());
1866 ASSERT_TRUE(client.setUp(GetParam()));
1867
1868 ASSERT_EQ(OK, trust(&client, server));
1869
1870 server->start();
1871
1872 // For TLS, Client should be able to verify server's identity, so client should see
1873 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1874 // identity and should drop the connection, so client shouldn't be able to read anything.
1875 bool readOk = rpcSecurity != RpcSecurity::TLS;
1876 client.run(true, readOk);
1877 }
1878
TEST_P(RpcTransportTest,MaliciousClient)1879 TEST_P(RpcTransportTest, MaliciousClient) {
1880 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1881 auto server = std::make_unique<Server>();
1882 ASSERT_TRUE(server->setUp(GetParam()));
1883
1884 Client validClient(server->getConnectToServerFn());
1885 ASSERT_TRUE(validClient.setUp(GetParam()));
1886 Client maliciousClient(server->getConnectToServerFn());
1887 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
1888
1889 ASSERT_EQ(OK, trust(&validClient, server));
1890 ASSERT_EQ(OK, trust(&maliciousClient, server));
1891
1892 server->start();
1893
1894 // See UntrustedClient.
1895 bool readOk = rpcSecurity != RpcSecurity::TLS;
1896 maliciousClient.run(true, readOk);
1897 }
1898
TEST_P(RpcTransportTest,Trigger)1899 TEST_P(RpcTransportTest, Trigger) {
1900 std::string msg2 = ", world!";
1901 std::mutex writeMutex;
1902 std::condition_variable writeCv;
1903 bool shouldContinueWriting = false;
1904 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1905 std::string message(RpcTransportTestUtils::kMessage);
1906 iovec messageIov{message.data(), message.size()};
1907 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, {});
1908 if (status != OK) return AssertionFailure() << statusToString(status);
1909
1910 {
1911 std::unique_lock<std::mutex> lock(writeMutex);
1912 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1913 return AssertionFailure() << "write barrier not cleared in time!";
1914 }
1915 }
1916
1917 iovec msg2Iov{msg2.data(), msg2.size()};
1918 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, {});
1919 if (status != DEAD_OBJECT)
1920 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
1921 "should return DEAD_OBJECT, but it is "
1922 << statusToString(status);
1923 return AssertionSuccess();
1924 };
1925
1926 auto server = std::make_unique<Server>();
1927 ASSERT_TRUE(server->setUp(GetParam()));
1928
1929 // Set up client
1930 Client client(server->getConnectToServerFn());
1931 ASSERT_TRUE(client.setUp(GetParam()));
1932
1933 // Exchange keys
1934 ASSERT_EQ(OK, trust(&client, server));
1935 ASSERT_EQ(OK, trust(server, &client));
1936
1937 server->setPostConnect(serverPostConnect);
1938
1939 server->start();
1940 // connect() to server and do handshake
1941 ASSERT_TRUE(client.setUpTransport());
1942 // read the first message. This ensures that server has finished handshake and start handling
1943 // client fd. Server thread should pause at writeCv.wait_for().
1944 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1945 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1946 // write is on an FdTrigger that has been shut down.
1947 server->shutdown();
1948 // Continues server thread to write the second message.
1949 {
1950 std::lock_guard<std::mutex> lock(writeMutex);
1951 shouldContinueWriting = true;
1952 }
1953 writeCv.notify_all();
1954 // After this line, server thread unblocks and attempts to write the second message, but
1955 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
1956 // On the client side, second read fails with DEAD_OBJECT
1957 ASSERT_FALSE(client.readMessage(msg2));
1958 }
1959
1960 INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
1961 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
1962 RpcTransportTest::PrintParamInfo);
1963
1964 class RpcTransportTlsKeyTest
1965 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1966 public:
1967 template <typename A, typename B>
trust(const A & a,const B & b)1968 status_t trust(const A& a, const B& b) {
1969 auto [socketType, certificateFormat, keyFormat] = GetParam();
1970 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1971 }
PrintParamInfo(const testing::TestParamInfo<ParamType> & info)1972 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1973 auto [socketType, certificateFormat, keyFormat] = info.param;
1974 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1975 "_key_" + PrintToString(keyFormat);
1976 return ret;
1977 };
1978 };
1979
TEST_P(RpcTransportTlsKeyTest,PreSignedCertificate)1980 TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1981 auto [socketType, certificateFormat, keyFormat] = GetParam();
1982
1983 std::vector<uint8_t> pkeyData, certData;
1984 {
1985 auto pkey = makeKeyPairForSelfSignedCert();
1986 ASSERT_NE(nullptr, pkey);
1987 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1988 ASSERT_NE(nullptr, cert);
1989 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1990 certData = serializeCertificate(cert.get(), certificateFormat);
1991 }
1992
1993 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1994 auto desCert = deserializeCertificate(certData, certificateFormat);
1995 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1996 auto utilsParam =
1997 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1998
1999 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2000 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2001
2002 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2003 ASSERT_TRUE(client.setUp(utilsParam));
2004
2005 ASSERT_EQ(OK, trust(&client, server));
2006 ASSERT_EQ(OK, trust(server, &client));
2007
2008 server->start();
2009 client.run();
2010 }
2011
2012 INSTANTIATE_TEST_CASE_P(
2013 BinderRpc, RpcTransportTlsKeyTest,
2014 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2015 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
2016 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
2017 RpcTransportTlsKeyTest::PrintParamInfo);
2018
2019 } // namespace android
2020
main(int argc,char ** argv)2021 int main(int argc, char** argv) {
2022 ::testing::InitGoogleTest(&argc, argv);
2023 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
2024
2025 return RUN_ALL_TESTS();
2026 }
2027