blob: 2011801f279820c6c9e47007af0e145188a67c79 [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>
Steven Moreland37aff182021-03-26 02:04:16 +000025#include <android/binder_auto_utils.h>
26#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/Binder.h>
28#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000029#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/IServiceManager.h>
31#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000033#include <binder/RpcSession.h>
Yifan Honge0e53282021-09-23 18:37:21 -070034#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070035#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070036#include <binder/RpcTransport.h>
37#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070038#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000039#include <gtest/gtest.h>
40
Steven Morelandc1635952021-04-01 16:20:47 +000041#include <chrono>
42#include <cstdlib>
43#include <iostream>
44#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000045#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000046
Yifan Hong1deca4b2021-09-10 16:16:44 -070047#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000048#include <sys/prctl.h>
49#include <unistd.h>
50
Yifan Hong1deca4b2021-09-10 16:16:44 -070051#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070052#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070053#include "../RpcState.h" // for debugging
54#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000055
Yifan Hong1a235852021-05-13 16:07:47 -070056using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070057using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070058using testing::AssertionFailure;
59using testing::AssertionResult;
60using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070061
Steven Moreland5553ac42020-11-11 02:14:45 +000062namespace android {
63
Steven Morelandbf57bce2021-07-26 15:26:12 -070064static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
65 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000066const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070067
Yifan Hong92409752021-07-30 21:25:32 -070068enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070069
70static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070071 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070072}
73
Yifan Hong13c90062021-09-09 14:59:53 -070074static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070075 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
76 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070077 switch (rpcSecurity) {
78 case RpcSecurity::RAW:
79 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070080 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070081 if (verifier == nullptr) {
82 verifier = std::make_shared<RpcCertificateVerifierSimple>();
83 }
Yifan Hongffdaf952021-09-17 18:08:38 -070084 if (auth == nullptr) {
85 auth = std::make_unique<RpcAuthSelfSigned>();
86 }
87 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -070088 }
Yifan Hong702115c2021-06-24 15:39:18 -070089 default:
90 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
91 }
92}
93
Steven Moreland1fda67b2021-04-02 18:35:50 +000094TEST(BinderRpcParcel, EntireParcelFormatted) {
95 Parcel p;
96 p.writeInt32(3);
97
98 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
99}
100
Yifan Hong702115c2021-06-24 15:39:18 -0700101class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
102public:
103 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
104 return newFactory(info.param)->toCString();
105 }
106};
107
108TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700109 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
110 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -0700111 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700112 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
113 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700114 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700115 ASSERT_TRUE(server->hasServer());
116 base::unique_fd retrieved = server->releaseServer();
117 ASSERT_FALSE(server->hasServer());
118 ASSERT_EQ(sinkFd, retrieved.get());
119}
120
Steven Morelandbf57bce2021-07-26 15:26:12 -0700121TEST(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
129TEST(BinderRpc, CanUseExperimentalWireVersion) {
130 auto session = RpcSession::make();
131 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
132}
133
Steven Moreland5553ac42020-11-11 02:14:45 +0000134using 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
142class MyBinderRpcSession : public BnBinderRpcSession {
143public:
144 static std::atomic<int32_t> gNum;
145
146 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
147 Status getName(std::string* name) override {
148 *name = mName;
149 return Status::ok();
150 }
151 ~MyBinderRpcSession() { gNum--; }
152
153private:
154 std::string mName;
155};
156std::atomic<int32_t> MyBinderRpcSession::gNum;
157
Steven Moreland659416d2021-05-11 00:47:50 +0000158class MyBinderRpcCallback : public BnBinderRpcCallback {
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 }
166 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
167
168public:
169 std::mutex mMutex;
170 std::condition_variable mCv;
171 std::vector<std::string> mValues;
172};
173
Steven Moreland5553ac42020-11-11 02:14:45 +0000174class MyBinderRpcTest : public BnBinderRpcTest {
175public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000176 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000177
178 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000179 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000180 return Status::ok();
181 }
182 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 *strstr = str + str;
184 return Status::ok();
185 }
Steven Moreland736664b2021-05-01 04:27:25 +0000186 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000187 sp<RpcServer> spServer = server.promote();
188 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000189 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
190 }
Steven Moreland736664b2021-05-01 04:27:25 +0000191 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192 for (auto session : spServer->listSessions()) {
193 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000194 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000195 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 return Status::ok();
197 }
198 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
199 if (binder == nullptr) {
200 std::cout << "Received null binder!" << std::endl;
201 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
202 }
203 *out = binder->pingBinder();
204 return Status::ok();
205 }
206 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
207 *out = binder;
208 return Status::ok();
209 }
210 static sp<IBinder> mHeldBinder;
211 Status holdBinder(const sp<IBinder>& binder) override {
212 mHeldBinder = binder;
213 return Status::ok();
214 }
215 Status getHeldBinder(sp<IBinder>* held) override {
216 *held = mHeldBinder;
217 return Status::ok();
218 }
219 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
220 if (count <= 0) return Status::ok();
221 return binder->nestMe(this, count - 1);
222 }
223 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
224 static sp<IBinder> binder = new BBinder;
225 *out = binder;
226 return Status::ok();
227 }
228 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
229 *out = new MyBinderRpcSession(name);
230 return Status::ok();
231 }
232 Status getNumOpenSessions(int32_t* out) override {
233 *out = MyBinderRpcSession::gNum;
234 return Status::ok();
235 }
236
237 std::mutex blockMutex;
238 Status lock() override {
239 blockMutex.lock();
240 return Status::ok();
241 }
242 Status unlockInMsAsync(int32_t ms) override {
243 usleep(ms * 1000);
244 blockMutex.unlock();
245 return Status::ok();
246 }
247 Status lockUnlock() override {
248 std::lock_guard<std::mutex> _l(blockMutex);
249 return Status::ok();
250 }
251
252 Status sleepMs(int32_t ms) override {
253 usleep(ms * 1000);
254 return Status::ok();
255 }
256
257 Status sleepMsAsync(int32_t ms) override {
258 // In-process binder calls are asynchronous, but the call to this method
259 // is synchronous wrt its client. This in/out-process threading model
260 // diffentiation is a classic binder leaky abstraction (for better or
261 // worse) and is preserved here the way binder sockets plugs itself
262 // into BpBinder, as nothing is changed at the higher levels
263 // (IInterface) which result in this behavior.
264 return sleepMs(ms);
265 }
266
Steven Moreland659416d2021-05-11 00:47:50 +0000267 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
268 const std::string& value) override {
269 if (callback == nullptr) {
270 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
271 }
272
273 if (delayed) {
274 std::thread([=]() {
275 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000276 Status status = doCallback(callback, oneway, false, value);
277 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000278 }).detach();
279 return Status::ok();
280 }
281
282 if (oneway) {
283 return callback->sendOnewayCallback(value);
284 }
285
286 return callback->sendCallback(value);
287 }
288
Steven Morelandc7d40132021-06-10 03:42:11 +0000289 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
290 const std::string& value) override {
291 return doCallback(callback, oneway, delayed, value);
292 }
293
Steven Moreland5553ac42020-11-11 02:14:45 +0000294 Status die(bool cleanup) override {
295 if (cleanup) {
296 exit(1);
297 } else {
298 _exit(1);
299 }
300 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000301
302 Status scheduleShutdown() override {
303 sp<RpcServer> strongServer = server.promote();
304 if (strongServer == nullptr) {
305 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
306 }
307 std::thread([=] {
308 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
309 }).detach();
310 return Status::ok();
311 }
312
Steven Morelandd7302072021-05-15 01:32:04 +0000313 Status useKernelBinderCallingId() override {
314 // this is WRONG! It does not make sense when using RPC binder, and
315 // because it is SO wrong, and so much code calls this, it should abort!
316
317 (void)IPCThreadState::self()->getCallingPid();
318 return Status::ok();
319 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000320};
321sp<IBinder> MyBinderRpcTest::mHeldBinder;
322
323class Process {
324public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700325 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700326 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
327 android::base::borrowed_fd /* readEnd */)>& f) {
328 android::base::unique_fd childWriteEnd;
329 android::base::unique_fd childReadEnd;
330 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
331 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000332 if (0 == (mPid = fork())) {
333 // racey: assume parent doesn't crash before this is set
334 prctl(PR_SET_PDEATHSIG, SIGHUP);
335
Yifan Hong1deca4b2021-09-10 16:16:44 -0700336 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000337
338 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 }
340 }
341 ~Process() {
342 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000343 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000344 }
345 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700346 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700347 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000348
349private:
350 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700351 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000353};
354
355static std::string allocateSocketAddress() {
356 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000357 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
359 unlink(ret.c_str());
360 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000361};
362
Steven Morelandda573042021-06-12 01:13:45 +0000363static unsigned int allocateVsockPort() {
364 static unsigned int vsockPort = 3456;
365 return vsockPort++;
366}
367
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000368struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 // reference to process hosting a socket server
370 Process host;
371
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372 struct SessionInfo {
373 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000374 sp<IBinder> root;
375 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000376
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377 // client session objects associated with other process
378 // each one represents a separate session
379 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000380
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000381 ProcessSession(ProcessSession&&) = default;
382 ~ProcessSession() {
383 for (auto& session : sessions) {
384 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000385 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000386
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 for (auto& info : sessions) {
388 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000389
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000390 EXPECT_NE(nullptr, session);
391 EXPECT_NE(nullptr, session->state());
392 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000393
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 wp<RpcSession> weakSession = session;
395 session = nullptr;
396 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000397 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 }
399};
400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000402// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403struct BinderRpcTestProcessSession {
404 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000407 sp<IBinder> rootBinder;
408
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000410 sp<IBinderRpcTest> rootIface;
411
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000413 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000414
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
416 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000417 EXPECT_NE(nullptr, rootIface);
418 if (rootIface == nullptr) return;
419
Steven Morelandaf4ca712021-05-24 23:22:08 +0000420 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000421 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000423 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000424 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000425 for (auto remoteCount : remoteCounts) {
426 EXPECT_EQ(remoteCount, 1);
427 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000428
Steven Moreland798e0d12021-07-14 23:19:25 +0000429 // even though it is on another thread, shutdown races with
430 // the transaction reply being written
431 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
432 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
433 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000434 }
435
436 rootIface = nullptr;
437 rootBinder = nullptr;
438 }
439};
440
Steven Morelandc1635952021-04-01 16:20:47 +0000441enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700442 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000443 UNIX,
444 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700445 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000446};
Yifan Hong702115c2021-06-24 15:39:18 -0700447static inline std::string PrintToString(SocketType socketType) {
448 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700449 case SocketType::PRECONNECTED:
450 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000451 case SocketType::UNIX:
452 return "unix_domain_socket";
453 case SocketType::VSOCK:
454 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700455 case SocketType::INET:
456 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000457 default:
458 LOG_ALWAYS_FATAL("Unknown socket type");
459 return "";
460 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000461}
Steven Morelandda573042021-06-12 01:13:45 +0000462
Yifan Hong1deca4b2021-09-10 16:16:44 -0700463static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700464 base::unique_fd serverFd(
465 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
466 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700467 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
468 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700469
470 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
471 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700472 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
473 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700474 }
475 return serverFd;
476}
477
Yifan Hong702115c2021-06-24 15:39:18 -0700478class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000479public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000480 struct Options {
481 size_t numThreads = 1;
482 size_t numSessions = 1;
483 size_t numIncomingConnections = 0;
484 };
485
Yifan Hong702115c2021-06-24 15:39:18 -0700486 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
487 auto [type, security] = info.param;
488 return PrintToString(type) + "_" + newFactory(security)->toCString();
489 }
490
Yifan Hong1deca4b2021-09-10 16:16:44 -0700491 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
492 uint64_t length = str.length();
493 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
494 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
495 }
496
497 static inline std::string readString(android::base::borrowed_fd fd) {
498 uint64_t length;
499 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
500 std::string ret(length, '\0');
501 CHECK(android::base::ReadFully(fd, ret.data(), length));
502 return ret;
503 }
504
505 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
506 Parcel parcel;
507 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
508 writeString(fd,
509 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
510 }
511
512 template <typename T>
513 static inline T readFromFd(android::base::borrowed_fd fd) {
514 std::string data = readString(fd);
515 Parcel parcel;
516 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
517 T object;
518 CHECK_EQ(OK, object.readFromParcel(&parcel));
519 return object;
520 }
521
Steven Morelandc1635952021-04-01 16:20:47 +0000522 // This creates a new process serving an interface on a certain number of
523 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000524 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000525 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
526 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000527
Yifan Hong702115c2021-06-24 15:39:18 -0700528 SocketType socketType = std::get<0>(GetParam());
529 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000530
Steven Morelandda573042021-06-12 01:13:45 +0000531 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000532 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000533
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700535 .host = Process([&](android::base::borrowed_fd writeEnd,
536 android::base::borrowed_fd readEnd) {
537 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
538 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000539
540 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000541 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000542
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000543 unsigned int outPort = 0;
544
Steven Morelandc1635952021-04-01 16:20:47 +0000545 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700546 case SocketType::PRECONNECTED:
547 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000548 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700549 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000550 break;
551 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700552 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000553 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700554 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700555 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700556 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700557 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700558 }
Steven Morelandc1635952021-04-01 16:20:47 +0000559 default:
560 LOG_ALWAYS_FATAL("Unknown socket type");
561 }
562
Yifan Hong1deca4b2021-09-10 16:16:44 -0700563 BinderRpcTestServerInfo serverInfo;
564 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700565 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700566 writeToFd(writeEnd, serverInfo);
567 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
568
569 if (rpcSecurity == RpcSecurity::TLS) {
570 for (const auto& clientCert : clientInfo.certs) {
571 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700572 certVerifier
573 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
574 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700575 }
576 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000577
Steven Moreland611d15f2021-05-01 01:28:27 +0000578 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000579
Steven Morelandf137de92021-04-24 01:54:26 +0000580 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000581
582 // Another thread calls shutdown. Wait for it to complete.
583 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000584 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000585 };
586
Yifan Hong1deca4b2021-09-10 16:16:44 -0700587 std::vector<sp<RpcSession>> sessions;
588 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
589 for (size_t i = 0; i < options.numSessions; i++) {
590 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
591 }
592
593 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
594 BinderRpcTestClientInfo clientInfo;
595 for (const auto& session : sessions) {
596 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700597 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700598 }
599 writeToFd(ret.host.writeEnd(), clientInfo);
600
601 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700602 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700603 CHECK_NE(0, serverInfo.port);
604 }
605
606 if (rpcSecurity == RpcSecurity::TLS) {
607 const auto& serverCert = serverInfo.cert.data;
608 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700609 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
610 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700611 }
612
Steven Moreland2372f9d2021-08-05 15:42:01 -0700613 status_t status;
614
Yifan Hong1deca4b2021-09-10 16:16:44 -0700615 for (const auto& session : sessions) {
Yifan Hong10423062021-10-08 16:26:32 -0700616 session->setMaxIncomingThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000617
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000618 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700619 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700620 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700621 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700622 });
Steven Moreland4198a122021-08-03 17:37:58 -0700623 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000624 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700625 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000626 break;
627 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700628 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000629 break;
630 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700631 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000632 break;
633 default:
634 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000635 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700636 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000637 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000638 }
Steven Morelandc1635952021-04-01 16:20:47 +0000639 return ret;
640 }
641
Steven Moreland4313d7e2021-07-15 23:41:22 +0000642 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000643 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000644 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000645 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000646 sp<MyBinderRpcTest> service =
647 new MyBinderRpcTest;
648 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000649 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000650 }),
651 };
652
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000653 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000654 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
655
656 return ret;
657 }
658};
659
Steven Morelandc1635952021-04-01 16:20:47 +0000660TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000661 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000662 ASSERT_NE(proc.rootBinder, nullptr);
663 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
664}
665
Steven Moreland4cf688f2021-03-31 01:48:58 +0000666TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000667 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000668 ASSERT_NE(proc.rootBinder, nullptr);
669 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
670}
671
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000672TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000673 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000674 for (auto session : proc.proc.sessions) {
675 ASSERT_NE(nullptr, session.root);
676 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000677 }
678}
679
Steven Morelandc1635952021-04-01 16:20:47 +0000680TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000681 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000682 Parcel data;
683 Parcel reply;
684 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
685}
686
Steven Moreland67753c32021-04-02 18:45:19 +0000687TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000688 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000689
690 Parcel p1;
691 p1.markForBinder(proc.rootBinder);
692 p1.writeInt32(3);
693
694 Parcel p2;
695
696 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
697 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
698}
699
Steven Morelandc1635952021-04-01 16:20:47 +0000700TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000701 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000702 Parcel data;
703 data.markForBinder(proc.rootBinder);
704 Parcel reply;
705 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
706}
707
Steven Morelandc1635952021-04-01 16:20:47 +0000708TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000709 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 EXPECT_OK(proc.rootIface->sendString("asdf"));
711}
712
Steven Morelandc1635952021-04-01 16:20:47 +0000713TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000714 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000715 std::string doubled;
716 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
717 EXPECT_EQ("cool cool ", doubled);
718}
719
Steven Morelandc1635952021-04-01 16:20:47 +0000720TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000721 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000722 std::string single = std::string(1024, 'a');
723 std::string doubled;
724 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
725 EXPECT_EQ(single + single, doubled);
726}
727
Steven Morelandc1635952021-04-01 16:20:47 +0000728TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000729 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000730
731 int32_t pingResult;
732 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
733 EXPECT_EQ(OK, pingResult);
734
735 EXPECT_EQ(0, MyBinderRpcSession::gNum);
736}
737
Steven Morelandc1635952021-04-01 16:20:47 +0000738TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000739 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000740
741 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
742 sp<IBinder> outBinder;
743 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
744 EXPECT_EQ(inBinder, outBinder);
745
746 wp<IBinder> weak = inBinder;
747 inBinder = nullptr;
748 outBinder = nullptr;
749
750 // Force reading a reply, to process any pending dec refs from the other
751 // process (the other process will process dec refs there before processing
752 // the ping here).
753 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
754
755 EXPECT_EQ(nullptr, weak.promote());
756
757 EXPECT_EQ(0, MyBinderRpcSession::gNum);
758}
759
Steven Morelandc1635952021-04-01 16:20:47 +0000760TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000761 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000762
763 sp<IBinderRpcSession> session;
764 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
765
766 sp<IBinder> inBinder = IInterface::asBinder(session);
767 sp<IBinder> outBinder;
768 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
769 EXPECT_EQ(inBinder, outBinder);
770
771 wp<IBinder> weak = inBinder;
772 session = nullptr;
773 inBinder = nullptr;
774 outBinder = nullptr;
775
776 // Force reading a reply, to process any pending dec refs from the other
777 // process (the other process will process dec refs there before processing
778 // the ping here).
779 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
780
781 EXPECT_EQ(nullptr, weak.promote());
782}
783
Steven Morelandc1635952021-04-01 16:20:47 +0000784TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000785 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000786
787 sp<IBinder> outBinder;
788 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
789 EXPECT_EQ(nullptr, outBinder);
790}
791
Steven Morelandc1635952021-04-01 16:20:47 +0000792TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000793 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000794
795 IBinder* ptr = nullptr;
796 {
797 sp<IBinder> binder = new BBinder();
798 ptr = binder.get();
799 EXPECT_OK(proc.rootIface->holdBinder(binder));
800 }
801
802 sp<IBinder> held;
803 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
804
805 EXPECT_EQ(held.get(), ptr);
806
807 // stop holding binder, because we test to make sure references are cleaned
808 // up
809 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
810 // and flush ref counts
811 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
812}
813
814// START TESTS FOR LIMITATIONS OF SOCKET BINDER
815// These are behavioral differences form regular binder, where certain usecases
816// aren't supported.
817
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000818TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000819 auto proc1 = createRpcTestSocketServerProcess({});
820 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000821
822 sp<IBinder> outBinder;
823 EXPECT_EQ(INVALID_OPERATION,
824 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
825}
826
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000827TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000828 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000829
830 sp<IBinder> outBinder;
831 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000832 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000833 .transactionError());
834}
835
Steven Morelandc1635952021-04-01 16:20:47 +0000836TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000837 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000838
839 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
840 sp<IBinder> outBinder;
841 EXPECT_EQ(INVALID_OPERATION,
842 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
843}
844
Steven Morelandc1635952021-04-01 16:20:47 +0000845TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000846 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000847
848 // for historical reasons, IServiceManager interface only returns the
849 // exception code
850 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
851 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
852}
853
854// END TESTS FOR LIMITATIONS OF SOCKET BINDER
855
Steven Morelandc1635952021-04-01 16:20:47 +0000856TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000857 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000858
859 sp<IBinder> outBinder;
860 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
861 EXPECT_EQ(proc.rootBinder, outBinder);
862}
863
Steven Morelandc1635952021-04-01 16:20:47 +0000864TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000865 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000866
867 auto nastyNester = sp<MyBinderRpcTest>::make();
868 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
869
870 wp<IBinder> weak = nastyNester;
871 nastyNester = nullptr;
872 EXPECT_EQ(nullptr, weak.promote());
873}
874
Steven Morelandc1635952021-04-01 16:20:47 +0000875TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000876 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000877
878 sp<IBinder> a;
879 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
880
881 sp<IBinder> b;
882 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
883
884 EXPECT_EQ(a, b);
885}
886
Steven Morelandc1635952021-04-01 16:20:47 +0000887TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000888 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000889
890 sp<IBinder> a;
891 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
892 wp<IBinder> weak = a;
893 a = nullptr;
894
895 sp<IBinder> b;
896 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
897
898 // this is the wrong behavior, since BpBinder
899 // doesn't implement onIncStrongAttempted
900 // but make sure there is no crash
901 EXPECT_EQ(nullptr, weak.promote());
902
903 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
904
905 // In order to fix this:
906 // - need to have incStrongAttempted reflected across IPC boundary (wait for
907 // response to promote - round trip...)
908 // - sendOnLastWeakRef, to delete entries out of RpcState table
909 EXPECT_EQ(b, weak.promote());
910}
911
912#define expectSessions(expected, iface) \
913 do { \
914 int session; \
915 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
916 EXPECT_EQ(expected, session); \
917 } while (false)
918
Steven Morelandc1635952021-04-01 16:20:47 +0000919TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000920 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000921
922 sp<IBinderRpcSession> session;
923 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
924 std::string out;
925 EXPECT_OK(session->getName(&out));
926 EXPECT_EQ("aoeu", out);
927
928 expectSessions(1, proc.rootIface);
929 session = nullptr;
930 expectSessions(0, proc.rootIface);
931}
932
Steven Morelandc1635952021-04-01 16:20:47 +0000933TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000935
936 std::vector<sp<IBinderRpcSession>> sessions;
937
938 for (size_t i = 0; i < 15; i++) {
939 expectSessions(i, proc.rootIface);
940 sp<IBinderRpcSession> session;
941 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
942 sessions.push_back(session);
943 }
944 expectSessions(sessions.size(), proc.rootIface);
945 for (size_t i = 0; i < sessions.size(); i++) {
946 std::string out;
947 EXPECT_OK(sessions.at(i)->getName(&out));
948 EXPECT_EQ(std::to_string(i), out);
949 }
950 expectSessions(sessions.size(), proc.rootIface);
951
952 while (!sessions.empty()) {
953 sessions.pop_back();
954 expectSessions(sessions.size(), proc.rootIface);
955 }
956 expectSessions(0, proc.rootIface);
957}
958
959size_t epochMillis() {
960 using std::chrono::duration_cast;
961 using std::chrono::milliseconds;
962 using std::chrono::seconds;
963 using std::chrono::system_clock;
964 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
965}
966
Steven Morelandc1635952021-04-01 16:20:47 +0000967TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000968 constexpr size_t kNumThreads = 10;
969
Steven Moreland4313d7e2021-07-15 23:41:22 +0000970 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000971
972 EXPECT_OK(proc.rootIface->lock());
973
974 // block all but one thread taking locks
975 std::vector<std::thread> ts;
976 for (size_t i = 0; i < kNumThreads - 1; i++) {
977 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
978 }
979
980 usleep(100000); // give chance for calls on other threads
981
982 // other calls still work
983 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
984
985 constexpr size_t blockTimeMs = 500;
986 size_t epochMsBefore = epochMillis();
987 // after this, we should never see a response within this time
988 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
989
990 // this call should be blocked for blockTimeMs
991 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
992
993 size_t epochMsAfter = epochMillis();
994 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
995
996 for (auto& t : ts) t.join();
997}
998
Steven Morelandc1635952021-04-01 16:20:47 +0000999TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001000 constexpr size_t kNumThreads = 10;
1001 constexpr size_t kNumCalls = kNumThreads + 3;
1002 constexpr size_t kSleepMs = 500;
1003
Steven Moreland4313d7e2021-07-15 23:41:22 +00001004 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001005
1006 size_t epochMsBefore = epochMillis();
1007
1008 std::vector<std::thread> ts;
1009 for (size_t i = 0; i < kNumCalls; i++) {
1010 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
1011 }
1012
1013 for (auto& t : ts) t.join();
1014
1015 size_t epochMsAfter = epochMillis();
1016
1017 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
1018
1019 // Potential flake, but make sure calls are handled in parallel.
1020 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
1021}
1022
Steven Morelandc1635952021-04-01 16:20:47 +00001023TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001024 constexpr size_t kNumClientThreads = 10;
1025 constexpr size_t kNumServerThreads = 10;
1026 constexpr size_t kNumCalls = 100;
1027
Steven Moreland4313d7e2021-07-15 23:41:22 +00001028 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001029
1030 std::vector<std::thread> threads;
1031 for (size_t i = 0; i < kNumClientThreads; i++) {
1032 threads.push_back(std::thread([&] {
1033 for (size_t j = 0; j < kNumCalls; j++) {
1034 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001035 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001036 EXPECT_EQ(proc.rootBinder, out);
1037 }
1038 }));
1039 }
1040
1041 for (auto& t : threads) t.join();
1042}
1043
Steven Moreland925ba0a2021-09-17 18:06:32 -07001044static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1045 std::vector<std::thread> threads;
1046 for (size_t i = 0; i < threadCount; i++) {
1047 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1048 }
1049 for (auto& t : threads) t.join();
1050}
1051
Steven Morelandc6046982021-04-20 00:49:42 +00001052TEST_P(BinderRpc, OnewayStressTest) {
1053 constexpr size_t kNumClientThreads = 10;
1054 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001055 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001056
Steven Moreland4313d7e2021-07-15 23:41:22 +00001057 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001058
1059 std::vector<std::thread> threads;
1060 for (size_t i = 0; i < kNumClientThreads; i++) {
1061 threads.push_back(std::thread([&] {
1062 for (size_t j = 0; j < kNumCalls; j++) {
1063 EXPECT_OK(proc.rootIface->sendString("a"));
1064 }
Steven Morelandc6046982021-04-20 00:49:42 +00001065 }));
1066 }
1067
1068 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001069
1070 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001071}
1072
Steven Morelandc1635952021-04-01 16:20:47 +00001073TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001074 constexpr size_t kReallyLongTimeMs = 100;
1075 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1076
Steven Moreland4313d7e2021-07-15 23:41:22 +00001077 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001078
1079 size_t epochMsBefore = epochMillis();
1080
1081 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1082
1083 size_t epochMsAfter = epochMillis();
1084 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1085}
1086
Steven Morelandc1635952021-04-01 16:20:47 +00001087TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001088 constexpr size_t kNumSleeps = 10;
1089 constexpr size_t kNumExtraServerThreads = 4;
1090 constexpr size_t kSleepMs = 50;
1091
1092 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001093 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001094
1095 EXPECT_OK(proc.rootIface->lock());
1096
Steven Moreland1c678802021-09-17 16:48:47 -07001097 size_t epochMsBefore = epochMillis();
1098
1099 // all these *Async commands should be queued on the server sequentially,
1100 // even though there are multiple threads.
1101 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001102 proc.rootIface->sleepMsAsync(kSleepMs);
1103 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001104 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1105
Steven Moreland1c678802021-09-17 16:48:47 -07001106 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001107 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001108
Steven Moreland5553ac42020-11-11 02:14:45 +00001109 size_t epochMsAfter = epochMillis();
1110
1111 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001112
Steven Moreland925ba0a2021-09-17 18:06:32 -07001113 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001114}
1115
Steven Morelandd45be622021-06-04 02:19:37 +00001116TEST_P(BinderRpc, OnewayCallExhaustion) {
1117 constexpr size_t kNumClients = 2;
1118 constexpr size_t kTooLongMs = 1000;
1119
Steven Moreland4313d7e2021-07-15 23:41:22 +00001120 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001121
1122 // Build up oneway calls on the second session to make sure it terminates
1123 // and shuts down. The first session should be unaffected (proc destructor
1124 // checks the first session).
1125 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1126
1127 std::vector<std::thread> threads;
1128 for (size_t i = 0; i < kNumClients; i++) {
1129 // one of these threads will get stuck queueing a transaction once the
1130 // socket fills up, the other will be able to fill up transactions on
1131 // this object
1132 threads.push_back(std::thread([&] {
1133 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1134 }
1135 }));
1136 }
1137 for (auto& t : threads) t.join();
1138
1139 Status status = iface->sleepMsAsync(kTooLongMs);
1140 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1141
Steven Moreland798e0d12021-07-14 23:19:25 +00001142 // now that it has died, wait for the remote session to shutdown
1143 std::vector<int32_t> remoteCounts;
1144 do {
1145 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1146 } while (remoteCounts.size() == kNumClients);
1147
Steven Morelandd45be622021-06-04 02:19:37 +00001148 // the second session should be shutdown in the other process by the time we
1149 // are able to join above (it'll only be hung up once it finishes processing
1150 // any pending commands). We need to erase this session from the record
1151 // here, so that the destructor for our session won't check that this
1152 // session is valid, but we still want it to test the other session.
1153 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1154}
1155
Steven Moreland659416d2021-05-11 00:47:50 +00001156TEST_P(BinderRpc, Callbacks) {
1157 const static std::string kTestString = "good afternoon!";
1158
Steven Morelandc7d40132021-06-10 03:42:11 +00001159 for (bool callIsOneway : {true, false}) {
1160 for (bool callbackIsOneway : {true, false}) {
1161 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001162 auto proc = createRpcTestSocketServerProcess(
1163 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001164 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001165
Steven Morelandc7d40132021-06-10 03:42:11 +00001166 if (callIsOneway) {
1167 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1168 kTestString));
1169 } else {
1170 EXPECT_OK(
1171 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1172 }
Steven Moreland659416d2021-05-11 00:47:50 +00001173
Steven Morelandc7d40132021-06-10 03:42:11 +00001174 using std::literals::chrono_literals::operator""s;
1175 std::unique_lock<std::mutex> _l(cb->mMutex);
1176 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001177
Steven Morelandc7d40132021-06-10 03:42:11 +00001178 EXPECT_EQ(cb->mValues.size(), 1)
1179 << "callIsOneway: " << callIsOneway
1180 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1181 if (cb->mValues.empty()) continue;
1182 EXPECT_EQ(cb->mValues.at(0), kTestString)
1183 << "callIsOneway: " << callIsOneway
1184 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001185
Steven Morelandc7d40132021-06-10 03:42:11 +00001186 // since we are severing the connection, we need to go ahead and
1187 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001188 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1189 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1190 }
Steven Moreland659416d2021-05-11 00:47:50 +00001191
Steven Moreland1b304292021-07-15 22:59:34 +00001192 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001193 // need to manually shut it down
1194 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001195
Steven Morelandc7d40132021-06-10 03:42:11 +00001196 proc.expectAlreadyShutdown = true;
1197 }
Steven Moreland659416d2021-05-11 00:47:50 +00001198 }
1199 }
1200}
1201
Steven Moreland195edb82021-06-08 02:44:39 +00001202TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001203 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001204 auto cb = sp<MyBinderRpcCallback>::make();
1205
1206 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1207 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1208}
1209
Steven Morelandc1635952021-04-01 16:20:47 +00001210TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001211 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001212 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001213
1214 // make sure there is some state during crash
1215 // 1. we hold their binder
1216 sp<IBinderRpcSession> session;
1217 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1218 // 2. they hold our binder
1219 sp<IBinder> binder = new BBinder();
1220 EXPECT_OK(proc.rootIface->holdBinder(binder));
1221
1222 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1223 << "Do death cleanup: " << doDeathCleanup;
1224
Steven Morelandaf4ca712021-05-24 23:22:08 +00001225 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001226 }
1227}
1228
Steven Morelandd7302072021-05-15 01:32:04 +00001229TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001230 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001231
1232 // we can't allocate IPCThreadState so actually the first time should
1233 // succeed :(
1234 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1235
1236 // second time! we catch the error :)
1237 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1238
Steven Morelandaf4ca712021-05-24 23:22:08 +00001239 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001240}
1241
Steven Moreland37aff182021-03-26 02:04:16 +00001242TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001243 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001244
1245 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1246 ASSERT_NE(binder, nullptr);
1247
1248 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1249}
1250
1251TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001252 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001253
1254 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1255 ASSERT_NE(binder, nullptr);
1256
1257 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1258 ASSERT_NE(ndkBinder, nullptr);
1259
1260 std::string out;
1261 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1262 ASSERT_TRUE(status.isOk()) << status.getDescription();
1263 ASSERT_EQ("aoeuaoeu", out);
1264}
1265
Steven Moreland5553ac42020-11-11 02:14:45 +00001266ssize_t countFds() {
1267 DIR* dir = opendir("/proc/self/fd/");
1268 if (dir == nullptr) return -1;
1269 ssize_t ret = 0;
1270 dirent* ent;
1271 while ((ent = readdir(dir)) != nullptr) ret++;
1272 closedir(dir);
1273 return ret;
1274}
1275
Steven Morelandc1635952021-04-01 16:20:47 +00001276TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001277 ssize_t beforeFds = countFds();
1278 ASSERT_GE(beforeFds, 0);
1279 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001280 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001281 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1282 }
1283 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1284}
1285
Steven Morelandda573042021-06-12 01:13:45 +00001286static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001287 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001288 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001289 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001290 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001291 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1292 if (status == -EAFNOSUPPORT) {
1293 return false;
1294 }
1295 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1296 }
Steven Morelandda573042021-06-12 01:13:45 +00001297 server->start();
1298
Yifan Hongfdd9f692021-09-09 15:12:52 -07001299 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001300 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001301 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001302 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1303 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001304}
1305
Yifan Hong1deca4b2021-09-10 16:16:44 -07001306static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1307 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1308
1309 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001310
1311 static bool hasVsockLoopback = testSupportVsockLoopback();
1312
1313 if (hasVsockLoopback) {
1314 ret.push_back(SocketType::VSOCK);
1315 }
1316
1317 return ret;
1318}
1319
Yifan Hong702115c2021-06-24 15:39:18 -07001320INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1321 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1322 ::testing::ValuesIn(RpcSecurityValues())),
1323 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001324
Yifan Hong702115c2021-06-24 15:39:18 -07001325class BinderRpcServerRootObject
1326 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001327
1328TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1329 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1330 auto setRootObject = [](bool isStrong) -> SetFn {
1331 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1332 };
1333
Yifan Hong702115c2021-06-24 15:39:18 -07001334 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1335 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001336 auto binder1 = sp<BBinder>::make();
1337 IBinder* binderRaw1 = binder1.get();
1338 setRootObject(isStrong1)(server.get(), binder1);
1339 EXPECT_EQ(binderRaw1, server->getRootObject());
1340 binder1.clear();
1341 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1342
1343 auto binder2 = sp<BBinder>::make();
1344 IBinder* binderRaw2 = binder2.get();
1345 setRootObject(isStrong2)(server.get(), binder2);
1346 EXPECT_EQ(binderRaw2, server->getRootObject());
1347 binder2.clear();
1348 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1349}
1350
1351INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001352 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1353 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001354
Yifan Hong1a235852021-05-13 16:07:47 -07001355class OneOffSignal {
1356public:
1357 // If notify() was previously called, or is called within |duration|, return true; else false.
1358 template <typename R, typename P>
1359 bool wait(std::chrono::duration<R, P> duration) {
1360 std::unique_lock<std::mutex> lock(mMutex);
1361 return mCv.wait_for(lock, duration, [this] { return mValue; });
1362 }
1363 void notify() {
1364 std::unique_lock<std::mutex> lock(mMutex);
1365 mValue = true;
1366 lock.unlock();
1367 mCv.notify_all();
1368 }
1369
1370private:
1371 std::mutex mMutex;
1372 std::condition_variable mCv;
1373 bool mValue = false;
1374};
1375
Yifan Hong702115c2021-06-24 15:39:18 -07001376TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001377 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001378 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001379 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001380 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001381 auto joinEnds = std::make_shared<OneOffSignal>();
1382
1383 // If things are broken and the thread never stops, don't block other tests. Because the thread
1384 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1385 // shared pointers are passed.
1386 std::thread([server, joinEnds] {
1387 server->join();
1388 joinEnds->notify();
1389 }).detach();
1390
1391 bool shutdown = false;
1392 for (int i = 0; i < 10 && !shutdown; i++) {
1393 usleep(300 * 1000); // 300ms; total 3s
1394 if (server->shutdown()) shutdown = true;
1395 }
1396 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1397
1398 ASSERT_TRUE(joinEnds->wait(2s))
1399 << "After server->shutdown() returns true, join() did not stop after 2s";
1400}
1401
Yifan Hong194acf22021-06-29 18:44:56 -07001402TEST(BinderRpc, Java) {
1403#if !defined(__ANDROID__)
1404 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1405 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1406 "to binderHostDeviceTest. Hence, just disable this test on host.";
1407#endif // !__ANDROID__
1408 sp<IServiceManager> sm = defaultServiceManager();
1409 ASSERT_NE(nullptr, sm);
1410 // Any Java service with non-empty getInterfaceDescriptor() would do.
1411 // Let's pick batteryproperties.
1412 auto binder = sm->checkService(String16("batteryproperties"));
1413 ASSERT_NE(nullptr, binder);
1414 auto descriptor = binder->getInterfaceDescriptor();
1415 ASSERT_GE(descriptor.size(), 0);
1416 ASSERT_EQ(OK, binder->pingBinder());
1417
1418 auto rpcServer = RpcServer::make();
1419 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1420 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001421 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001422 auto socket = rpcServer->releaseServer();
1423
1424 auto keepAlive = sp<BBinder>::make();
1425 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1426
1427 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001428 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001429 auto rpcBinder = rpcSession->getRootObject();
1430 ASSERT_NE(nullptr, rpcBinder);
1431
1432 ASSERT_EQ(OK, rpcBinder->pingBinder());
1433
1434 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1435 << "getInterfaceDescriptor should not crash system_server";
1436 ASSERT_EQ(OK, rpcBinder->pingBinder());
1437}
1438
Yifan Hong702115c2021-06-24 15:39:18 -07001439INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1440 BinderRpcSimple::PrintTestParam);
1441
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001442class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001443public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001444 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001445 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001446
1447 // A server that handles client socket connections.
1448 class Server {
1449 public:
1450 explicit Server() {}
1451 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001452 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001453 [[nodiscard]] AssertionResult setUp(
1454 const Param& param,
1455 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1456 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001457 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1458 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1459 switch (socketType) {
1460 case SocketType::PRECONNECTED: {
1461 return AssertionFailure() << "Not supported by this test";
1462 } break;
1463 case SocketType::UNIX: {
1464 auto addr = allocateSocketAddress();
1465 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1466 if (status != OK) {
1467 return AssertionFailure()
1468 << "setupUnixDomainServer: " << statusToString(status);
1469 }
1470 mConnectToServer = [addr] {
1471 return connectTo(UnixSocketAddress(addr.c_str()));
1472 };
1473 } break;
1474 case SocketType::VSOCK: {
1475 auto port = allocateVsockPort();
1476 auto status = rpcServer->setupVsockServer(port);
1477 if (status != OK) {
1478 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1479 }
1480 mConnectToServer = [port] {
1481 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1482 };
1483 } break;
1484 case SocketType::INET: {
1485 unsigned int port;
1486 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1487 if (status != OK) {
1488 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1489 }
1490 mConnectToServer = [port] {
1491 const char* addr = kLocalInetAddress;
1492 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1493 if (aiStart == nullptr) return base::unique_fd{};
1494 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1495 auto fd = connectTo(
1496 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1497 if (fd.ok()) return fd;
1498 }
1499 ALOGE("None of the socket address resolved for %s:%u can be connected",
1500 addr, port);
1501 return base::unique_fd{};
1502 };
1503 }
1504 }
1505 mFd = rpcServer->releaseServer();
1506 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001507 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001508 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1509 mSetup = true;
1510 return AssertionSuccess();
1511 }
1512 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1513 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1514 return mCertVerifier;
1515 }
1516 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1517 void start() {
1518 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1519 mThread = std::make_unique<std::thread>(&Server::run, this);
1520 }
1521 void run() {
1522 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1523
1524 std::vector<std::thread> threads;
1525 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1526 base::unique_fd acceptedFd(
1527 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1528 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1529 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1530 }
1531
1532 for (auto& thread : threads) thread.join();
1533 }
1534 void handleOne(android::base::unique_fd acceptedFd) {
1535 ASSERT_TRUE(acceptedFd.ok());
1536 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1537 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001538 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539 }
Yifan Honge07d2732021-09-13 21:59:14 -07001540 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001541 shutdown();
1542 join();
1543 }
1544 void shutdown() { mFdTrigger->trigger(); }
1545
1546 void setPostConnect(
1547 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1548 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 }
1550
1551 private:
1552 std::unique_ptr<std::thread> mThread;
1553 ConnectToServer mConnectToServer;
1554 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1555 base::unique_fd mFd;
1556 std::unique_ptr<RpcTransportCtx> mCtx;
1557 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1558 std::make_shared<RpcCertificateVerifierSimple>();
1559 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001560 // The function invoked after connection and handshake. By default, it is
1561 // |defaultPostConnect| that sends |kMessage| to the client.
1562 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1563 Server::defaultPostConnect;
1564
1565 void join() {
1566 if (mThread != nullptr) {
1567 mThread->join();
1568 mThread = nullptr;
1569 }
1570 }
1571
1572 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1573 FdTrigger* fdTrigger) {
1574 std::string message(kMessage);
1575 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001576 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001577 if (status != OK) return AssertionFailure() << statusToString(status);
1578 return AssertionSuccess();
1579 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001580 };
1581
1582 class Client {
1583 public:
1584 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1585 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001586 [[nodiscard]] AssertionResult setUp(const Param& param) {
1587 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001588 mFdTrigger = FdTrigger::make();
1589 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1590 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1591 return AssertionSuccess();
1592 }
1593 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1594 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1595 return mCertVerifier;
1596 }
Yifan Hong67519322021-09-13 18:51:16 -07001597 // connect() and do handshake
1598 bool setUpTransport() {
1599 mFd = mConnectToServer();
1600 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1601 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1602 return mClientTransport != nullptr;
1603 }
1604 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1605 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1606 std::string readMessage(expectedMessage.size(), '\0');
1607 status_t readStatus =
1608 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001609 readMessage.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001610 if (readStatus != OK) {
1611 return AssertionFailure() << statusToString(readStatus);
1612 }
1613 if (readMessage != expectedMessage) {
1614 return AssertionFailure()
1615 << "Expected " << expectedMessage << ", actual " << readMessage;
1616 }
1617 return AssertionSuccess();
1618 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001620 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1622 return;
1623 }
1624 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001625 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001626 }
1627
1628 private:
1629 ConnectToServer mConnectToServer;
1630 base::unique_fd mFd;
1631 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1632 std::unique_ptr<RpcTransportCtx> mCtx;
1633 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1634 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001635 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001636 };
1637
1638 // Make A trust B.
1639 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001640 static status_t trust(RpcSecurity rpcSecurity,
1641 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1642 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001643 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001644 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1645 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1646 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001647 }
1648
1649 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001650};
1651
1652class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1653public:
1654 using Server = RpcTransportTestUtils::Server;
1655 using Client = RpcTransportTestUtils::Client;
1656 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1657 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1658 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1659 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1660 return ret;
1661 }
1662 static std::vector<ParamType> getRpcTranportTestParams() {
1663 std::vector<ParamType> ret;
1664 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1665 for (auto rpcSecurity : RpcSecurityValues()) {
1666 switch (rpcSecurity) {
1667 case RpcSecurity::RAW: {
1668 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1669 } break;
1670 case RpcSecurity::TLS: {
1671 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1672 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1673 } break;
1674 }
1675 }
1676 }
1677 return ret;
1678 }
1679 template <typename A, typename B>
1680 status_t trust(const A& a, const B& b) {
1681 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1682 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1683 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001684};
1685
1686TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001687 auto server = std::make_unique<Server>();
1688 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001689
1690 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001691 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001692
1693 ASSERT_EQ(OK, trust(&client, server));
1694 ASSERT_EQ(OK, trust(server, &client));
1695
1696 server->start();
1697 client.run();
1698}
1699
1700TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001701 auto server = std::make_unique<Server>();
1702 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001703
1704 std::vector<Client> clients;
1705 for (int i = 0; i < 2; i++) {
1706 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001707 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001708 ASSERT_EQ(OK, trust(&client, server));
1709 ASSERT_EQ(OK, trust(server, &client));
1710 }
1711
1712 server->start();
1713 for (auto& client : clients) client.run();
1714}
1715
1716TEST_P(RpcTransportTest, UntrustedServer) {
1717 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1718
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001719 auto untrustedServer = std::make_unique<Server>();
1720 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001721
1722 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001723 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724
1725 ASSERT_EQ(OK, trust(untrustedServer, &client));
1726
1727 untrustedServer->start();
1728
1729 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1730 // the client can't verify the server's identity.
1731 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1732 client.run(handshakeOk);
1733}
1734TEST_P(RpcTransportTest, MaliciousServer) {
1735 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001736 auto validServer = std::make_unique<Server>();
1737 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001739 auto maliciousServer = std::make_unique<Server>();
1740 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001741
1742 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001743 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001744
1745 ASSERT_EQ(OK, trust(&client, validServer));
1746 ASSERT_EQ(OK, trust(validServer, &client));
1747 ASSERT_EQ(OK, trust(maliciousServer, &client));
1748
1749 maliciousServer->start();
1750
1751 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1752 // the client can't verify the server's identity.
1753 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1754 client.run(handshakeOk);
1755}
1756
1757TEST_P(RpcTransportTest, UntrustedClient) {
1758 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001759 auto server = std::make_unique<Server>();
1760 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001761
1762 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001763 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001764
1765 ASSERT_EQ(OK, trust(&client, server));
1766
1767 server->start();
1768
1769 // For TLS, Client should be able to verify server's identity, so client should see
1770 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1771 // identity and should drop the connection, so client shouldn't be able to read anything.
1772 bool readOk = rpcSecurity != RpcSecurity::TLS;
1773 client.run(true, readOk);
1774}
1775
1776TEST_P(RpcTransportTest, MaliciousClient) {
1777 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001778 auto server = std::make_unique<Server>();
1779 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001780
1781 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001782 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001784 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001785
1786 ASSERT_EQ(OK, trust(&validClient, server));
1787 ASSERT_EQ(OK, trust(&maliciousClient, server));
1788
1789 server->start();
1790
1791 // See UntrustedClient.
1792 bool readOk = rpcSecurity != RpcSecurity::TLS;
1793 maliciousClient.run(true, readOk);
1794}
1795
Yifan Hong67519322021-09-13 18:51:16 -07001796TEST_P(RpcTransportTest, Trigger) {
1797 std::string msg2 = ", world!";
1798 std::mutex writeMutex;
1799 std::condition_variable writeCv;
1800 bool shouldContinueWriting = false;
1801 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001802 std::string message(RpcTransportTestUtils::kMessage);
Steven Moreland43921d52021-09-27 17:15:56 -07001803 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1804 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001805 if (status != OK) return AssertionFailure() << statusToString(status);
1806
1807 {
1808 std::unique_lock<std::mutex> lock(writeMutex);
1809 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1810 return AssertionFailure() << "write barrier not cleared in time!";
1811 }
1812 }
1813
Steven Moreland43921d52021-09-27 17:15:56 -07001814 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size(), {});
Steven Morelandc591b472021-09-16 13:56:11 -07001815 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001816 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001817 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001818 << statusToString(status);
1819 return AssertionSuccess();
1820 };
1821
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001822 auto server = std::make_unique<Server>();
1823 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001824
1825 // Set up client
1826 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001827 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001828
1829 // Exchange keys
1830 ASSERT_EQ(OK, trust(&client, server));
1831 ASSERT_EQ(OK, trust(server, &client));
1832
1833 server->setPostConnect(serverPostConnect);
1834
Yifan Hong67519322021-09-13 18:51:16 -07001835 server->start();
1836 // connect() to server and do handshake
1837 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001838 // read the first message. This ensures that server has finished handshake and start handling
1839 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001840 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001841 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1842 // write is on an FdTrigger that has been shut down.
1843 server->shutdown();
1844 // Continues server thread to write the second message.
1845 {
Yifan Hong22211f82021-09-14 12:32:25 -07001846 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001847 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001848 }
Yifan Hong22211f82021-09-14 12:32:25 -07001849 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001850 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001851 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001852 // On the client side, second read fails with DEAD_OBJECT
1853 ASSERT_FALSE(client.readMessage(msg2));
1854}
1855
Yifan Hong1deca4b2021-09-10 16:16:44 -07001856INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001857 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001858 RpcTransportTest::PrintParamInfo);
1859
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001860class RpcTransportTlsKeyTest
1861 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1862public:
1863 template <typename A, typename B>
1864 status_t trust(const A& a, const B& b) {
1865 auto [socketType, certificateFormat, keyFormat] = GetParam();
1866 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1867 }
1868 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1869 auto [socketType, certificateFormat, keyFormat] = info.param;
1870 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1871 "_key_" + PrintToString(keyFormat);
1872 return ret;
1873 };
1874};
1875
1876TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1877 auto [socketType, certificateFormat, keyFormat] = GetParam();
1878
1879 std::vector<uint8_t> pkeyData, certData;
1880 {
1881 auto pkey = makeKeyPairForSelfSignedCert();
1882 ASSERT_NE(nullptr, pkey);
1883 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1884 ASSERT_NE(nullptr, cert);
1885 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1886 certData = serializeCertificate(cert.get(), certificateFormat);
1887 }
1888
1889 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1890 auto desCert = deserializeCertificate(certData, certificateFormat);
1891 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1892 auto utilsParam =
1893 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1894
1895 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1896 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1897
1898 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1899 ASSERT_TRUE(client.setUp(utilsParam));
1900
1901 ASSERT_EQ(OK, trust(&client, server));
1902 ASSERT_EQ(OK, trust(server, &client));
1903
1904 server->start();
1905 client.run();
1906}
1907
1908INSTANTIATE_TEST_CASE_P(
1909 BinderRpc, RpcTransportTlsKeyTest,
1910 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1911 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
1912 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
1913 RpcTransportTlsKeyTest::PrintParamInfo);
1914
Steven Morelandc1635952021-04-01 16:20:47 +00001915} // namespace android
1916
1917int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001918 ::testing::InitGoogleTest(&argc, argv);
1919 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1920 return RUN_ALL_TESTS();
1921}