blob: cc1d2fae56a3e16fcaeee26ad974e977e7f941de [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 Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransport.h>
35#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070036#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000037#include <gtest/gtest.h>
38
Steven Morelandc1635952021-04-01 16:20:47 +000039#include <chrono>
40#include <cstdlib>
41#include <iostream>
42#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000043#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000044
Yifan Hong1deca4b2021-09-10 16:16:44 -070045#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000046#include <sys/prctl.h>
47#include <unistd.h>
48
Yifan Hong1deca4b2021-09-10 16:16:44 -070049#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070050#include "../RpcSocketAddress.h" // for testing preconnected clients
Steven Morelandbd5002b2021-05-04 23:12:56 +000051#include "../RpcState.h" // for debugging
52#include "../vm_sockets.h" // for VMADDR_*
Yifan Hong13c90062021-09-09 14:59:53 -070053#include "RpcCertificateVerifierSimple.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000054
Yifan Hong1a235852021-05-13 16:07:47 -070055using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070056using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070057using testing::AssertionFailure;
58using testing::AssertionResult;
59using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070060
Steven Moreland5553ac42020-11-11 02:14:45 +000061namespace android {
62
Steven Morelandbf57bce2021-07-26 15:26:12 -070063static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
64 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000065const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070066
Yifan Hong92409752021-07-30 21:25:32 -070067enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070068
69static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070070 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070071}
72
Yifan Hong13c90062021-09-09 14:59:53 -070073static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
74 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070075 switch (rpcSecurity) {
76 case RpcSecurity::RAW:
77 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070078 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070079 if (verifier == nullptr) {
80 verifier = std::make_shared<RpcCertificateVerifierSimple>();
81 }
82 return RpcTransportCtxFactoryTls::make(std::move(verifier));
83 }
Yifan Hong702115c2021-06-24 15:39:18 -070084 default:
85 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
86 }
87}
88
Steven Moreland1fda67b2021-04-02 18:35:50 +000089TEST(BinderRpcParcel, EntireParcelFormatted) {
90 Parcel p;
91 p.writeInt32(3);
92
93 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
94}
95
Yifan Hong702115c2021-06-24 15:39:18 -070096class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
97public:
98 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
99 return newFactory(info.param)->toCString();
100 }
101};
102
103TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700104 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
105 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -0700106 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700107 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
108 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700109 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700110 ASSERT_TRUE(server->hasServer());
111 base::unique_fd retrieved = server->releaseServer();
112 ASSERT_FALSE(server->hasServer());
113 ASSERT_EQ(sinkFd, retrieved.get());
114}
115
Steven Morelandbf57bce2021-07-26 15:26:12 -0700116TEST(BinderRpc, CannotUseNextWireVersion) {
117 auto session = RpcSession::make();
118 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
119 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
120 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
121 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
122}
123
124TEST(BinderRpc, CanUseExperimentalWireVersion) {
125 auto session = RpcSession::make();
126 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
127}
128
Steven Moreland5553ac42020-11-11 02:14:45 +0000129using android::binder::Status;
130
131#define EXPECT_OK(status) \
132 do { \
133 Status stat = (status); \
134 EXPECT_TRUE(stat.isOk()) << stat; \
135 } while (false)
136
137class MyBinderRpcSession : public BnBinderRpcSession {
138public:
139 static std::atomic<int32_t> gNum;
140
141 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
142 Status getName(std::string* name) override {
143 *name = mName;
144 return Status::ok();
145 }
146 ~MyBinderRpcSession() { gNum--; }
147
148private:
149 std::string mName;
150};
151std::atomic<int32_t> MyBinderRpcSession::gNum;
152
Steven Moreland659416d2021-05-11 00:47:50 +0000153class MyBinderRpcCallback : public BnBinderRpcCallback {
154 Status sendCallback(const std::string& value) {
155 std::unique_lock _l(mMutex);
156 mValues.push_back(value);
157 _l.unlock();
158 mCv.notify_one();
159 return Status::ok();
160 }
161 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
162
163public:
164 std::mutex mMutex;
165 std::condition_variable mCv;
166 std::vector<std::string> mValues;
167};
168
Steven Moreland5553ac42020-11-11 02:14:45 +0000169class MyBinderRpcTest : public BnBinderRpcTest {
170public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000171 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000172
173 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000174 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000175 return Status::ok();
176 }
177 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000178 *strstr = str + str;
179 return Status::ok();
180 }
Steven Moreland736664b2021-05-01 04:27:25 +0000181 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000182 sp<RpcServer> spServer = server.promote();
183 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000184 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
185 }
Steven Moreland736664b2021-05-01 04:27:25 +0000186 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000187 for (auto session : spServer->listSessions()) {
188 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000189 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000190 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 return Status::ok();
192 }
193 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
194 if (binder == nullptr) {
195 std::cout << "Received null binder!" << std::endl;
196 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
197 }
198 *out = binder->pingBinder();
199 return Status::ok();
200 }
201 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
202 *out = binder;
203 return Status::ok();
204 }
205 static sp<IBinder> mHeldBinder;
206 Status holdBinder(const sp<IBinder>& binder) override {
207 mHeldBinder = binder;
208 return Status::ok();
209 }
210 Status getHeldBinder(sp<IBinder>* held) override {
211 *held = mHeldBinder;
212 return Status::ok();
213 }
214 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
215 if (count <= 0) return Status::ok();
216 return binder->nestMe(this, count - 1);
217 }
218 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
219 static sp<IBinder> binder = new BBinder;
220 *out = binder;
221 return Status::ok();
222 }
223 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
224 *out = new MyBinderRpcSession(name);
225 return Status::ok();
226 }
227 Status getNumOpenSessions(int32_t* out) override {
228 *out = MyBinderRpcSession::gNum;
229 return Status::ok();
230 }
231
232 std::mutex blockMutex;
233 Status lock() override {
234 blockMutex.lock();
235 return Status::ok();
236 }
237 Status unlockInMsAsync(int32_t ms) override {
238 usleep(ms * 1000);
239 blockMutex.unlock();
240 return Status::ok();
241 }
242 Status lockUnlock() override {
243 std::lock_guard<std::mutex> _l(blockMutex);
244 return Status::ok();
245 }
246
247 Status sleepMs(int32_t ms) override {
248 usleep(ms * 1000);
249 return Status::ok();
250 }
251
252 Status sleepMsAsync(int32_t ms) override {
253 // In-process binder calls are asynchronous, but the call to this method
254 // is synchronous wrt its client. This in/out-process threading model
255 // diffentiation is a classic binder leaky abstraction (for better or
256 // worse) and is preserved here the way binder sockets plugs itself
257 // into BpBinder, as nothing is changed at the higher levels
258 // (IInterface) which result in this behavior.
259 return sleepMs(ms);
260 }
261
Steven Moreland659416d2021-05-11 00:47:50 +0000262 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
263 const std::string& value) override {
264 if (callback == nullptr) {
265 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
266 }
267
268 if (delayed) {
269 std::thread([=]() {
270 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000271 Status status = doCallback(callback, oneway, false, value);
272 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000273 }).detach();
274 return Status::ok();
275 }
276
277 if (oneway) {
278 return callback->sendOnewayCallback(value);
279 }
280
281 return callback->sendCallback(value);
282 }
283
Steven Morelandc7d40132021-06-10 03:42:11 +0000284 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
285 const std::string& value) override {
286 return doCallback(callback, oneway, delayed, value);
287 }
288
Steven Moreland5553ac42020-11-11 02:14:45 +0000289 Status die(bool cleanup) override {
290 if (cleanup) {
291 exit(1);
292 } else {
293 _exit(1);
294 }
295 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000296
297 Status scheduleShutdown() override {
298 sp<RpcServer> strongServer = server.promote();
299 if (strongServer == nullptr) {
300 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
301 }
302 std::thread([=] {
303 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
304 }).detach();
305 return Status::ok();
306 }
307
Steven Morelandd7302072021-05-15 01:32:04 +0000308 Status useKernelBinderCallingId() override {
309 // this is WRONG! It does not make sense when using RPC binder, and
310 // because it is SO wrong, and so much code calls this, it should abort!
311
312 (void)IPCThreadState::self()->getCallingPid();
313 return Status::ok();
314 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000315};
316sp<IBinder> MyBinderRpcTest::mHeldBinder;
317
318class Process {
319public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700320 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700321 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
322 android::base::borrowed_fd /* readEnd */)>& f) {
323 android::base::unique_fd childWriteEnd;
324 android::base::unique_fd childReadEnd;
325 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
326 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000327 if (0 == (mPid = fork())) {
328 // racey: assume parent doesn't crash before this is set
329 prctl(PR_SET_PDEATHSIG, SIGHUP);
330
Yifan Hong1deca4b2021-09-10 16:16:44 -0700331 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000332
333 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000334 }
335 }
336 ~Process() {
337 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000338 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 }
340 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700341 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700342 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000343
344private:
345 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700346 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700347 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000348};
349
350static std::string allocateSocketAddress() {
351 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000352 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700353 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
354 unlink(ret.c_str());
355 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000356};
357
Steven Morelandda573042021-06-12 01:13:45 +0000358static unsigned int allocateVsockPort() {
359 static unsigned int vsockPort = 3456;
360 return vsockPort++;
361}
362
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000363struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000364 // reference to process hosting a socket server
365 Process host;
366
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000367 struct SessionInfo {
368 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000369 sp<IBinder> root;
370 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000371
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372 // client session objects associated with other process
373 // each one represents a separate session
374 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000375
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 ProcessSession(ProcessSession&&) = default;
377 ~ProcessSession() {
378 for (auto& session : sessions) {
379 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000380 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 for (auto& info : sessions) {
383 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000384
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 EXPECT_NE(nullptr, session);
386 EXPECT_NE(nullptr, session->state());
387 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000388
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000389 wp<RpcSession> weakSession = session;
390 session = nullptr;
391 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000392 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000393 }
394};
395
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000396// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000397// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398struct BinderRpcTestProcessSession {
399 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 sp<IBinder> rootBinder;
403
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000405 sp<IBinderRpcTest> rootIface;
406
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000408 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000409
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
411 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000412 EXPECT_NE(nullptr, rootIface);
413 if (rootIface == nullptr) return;
414
Steven Morelandaf4ca712021-05-24 23:22:08 +0000415 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000416 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000418 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000419 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000420 for (auto remoteCount : remoteCounts) {
421 EXPECT_EQ(remoteCount, 1);
422 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000423
Steven Moreland798e0d12021-07-14 23:19:25 +0000424 // even though it is on another thread, shutdown races with
425 // the transaction reply being written
426 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
427 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
428 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000429 }
430
431 rootIface = nullptr;
432 rootBinder = nullptr;
433 }
434};
435
Steven Morelandc1635952021-04-01 16:20:47 +0000436enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700437 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000438 UNIX,
439 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700440 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000441};
Yifan Hong702115c2021-06-24 15:39:18 -0700442static inline std::string PrintToString(SocketType socketType) {
443 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700444 case SocketType::PRECONNECTED:
445 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000446 case SocketType::UNIX:
447 return "unix_domain_socket";
448 case SocketType::VSOCK:
449 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700450 case SocketType::INET:
451 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000452 default:
453 LOG_ALWAYS_FATAL("Unknown socket type");
454 return "";
455 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000456}
Steven Morelandda573042021-06-12 01:13:45 +0000457
Yifan Hong1deca4b2021-09-10 16:16:44 -0700458static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700459 base::unique_fd serverFd(
460 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
461 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700462 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
463 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700464
465 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
466 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700467 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
468 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700469 }
470 return serverFd;
471}
472
Yifan Hong702115c2021-06-24 15:39:18 -0700473class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000474public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000475 struct Options {
476 size_t numThreads = 1;
477 size_t numSessions = 1;
478 size_t numIncomingConnections = 0;
479 };
480
Yifan Hong702115c2021-06-24 15:39:18 -0700481 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
482 auto [type, security] = info.param;
483 return PrintToString(type) + "_" + newFactory(security)->toCString();
484 }
485
Yifan Hong1deca4b2021-09-10 16:16:44 -0700486 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
487 uint64_t length = str.length();
488 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
489 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
490 }
491
492 static inline std::string readString(android::base::borrowed_fd fd) {
493 uint64_t length;
494 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
495 std::string ret(length, '\0');
496 CHECK(android::base::ReadFully(fd, ret.data(), length));
497 return ret;
498 }
499
500 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
501 Parcel parcel;
502 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
503 writeString(fd,
504 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
505 }
506
507 template <typename T>
508 static inline T readFromFd(android::base::borrowed_fd fd) {
509 std::string data = readString(fd);
510 Parcel parcel;
511 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
512 T object;
513 CHECK_EQ(OK, object.readFromParcel(&parcel));
514 return object;
515 }
516
Steven Morelandc1635952021-04-01 16:20:47 +0000517 // This creates a new process serving an interface on a certain number of
518 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000520 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
521 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000522
Yifan Hong702115c2021-06-24 15:39:18 -0700523 SocketType socketType = std::get<0>(GetParam());
524 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000525
Steven Morelandda573042021-06-12 01:13:45 +0000526 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000527 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000528
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700530 .host = Process([&](android::base::borrowed_fd writeEnd,
531 android::base::borrowed_fd readEnd) {
532 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
533 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000534
535 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000536 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000537
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000538 unsigned int outPort = 0;
539
Steven Morelandc1635952021-04-01 16:20:47 +0000540 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700541 case SocketType::PRECONNECTED:
542 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000543 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700544 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000545 break;
546 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700547 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000548 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700549 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700551 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700552 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700553 }
Steven Morelandc1635952021-04-01 16:20:47 +0000554 default:
555 LOG_ALWAYS_FATAL("Unknown socket type");
556 }
557
Yifan Hong1deca4b2021-09-10 16:16:44 -0700558 BinderRpcTestServerInfo serverInfo;
559 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700560 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700561 writeToFd(writeEnd, serverInfo);
562 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
563
564 if (rpcSecurity == RpcSecurity::TLS) {
565 for (const auto& clientCert : clientInfo.certs) {
566 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700567 certVerifier
568 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
569 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700570 }
571 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000572
Steven Moreland611d15f2021-05-01 01:28:27 +0000573 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000574
Steven Morelandf137de92021-04-24 01:54:26 +0000575 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000576
577 // Another thread calls shutdown. Wait for it to complete.
578 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000579 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000580 };
581
Yifan Hong1deca4b2021-09-10 16:16:44 -0700582 std::vector<sp<RpcSession>> sessions;
583 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
584 for (size_t i = 0; i < options.numSessions; i++) {
585 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
586 }
587
588 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
589 BinderRpcTestClientInfo clientInfo;
590 for (const auto& session : sessions) {
591 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700592 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700593 }
594 writeToFd(ret.host.writeEnd(), clientInfo);
595
596 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700597 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700598 CHECK_NE(0, serverInfo.port);
599 }
600
601 if (rpcSecurity == RpcSecurity::TLS) {
602 const auto& serverCert = serverInfo.cert.data;
603 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700604 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
605 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700606 }
607
Steven Moreland2372f9d2021-08-05 15:42:01 -0700608 status_t status;
609
Yifan Hong1deca4b2021-09-10 16:16:44 -0700610 for (const auto& session : sessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000611 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000612
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000613 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700614 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700615 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700616 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700617 });
Steven Moreland4198a122021-08-03 17:37:58 -0700618 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000619 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700620 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000621 break;
622 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700623 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000624 break;
625 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700626 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000627 break;
628 default:
629 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000630 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700631 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000632 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000633 }
Steven Morelandc1635952021-04-01 16:20:47 +0000634 return ret;
635 }
636
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000638 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000639 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000640 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000641 sp<MyBinderRpcTest> service =
642 new MyBinderRpcTest;
643 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000644 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000645 }),
646 };
647
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000648 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000649 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
650
651 return ret;
652 }
653};
654
Steven Morelandc1635952021-04-01 16:20:47 +0000655TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000656 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000657 ASSERT_NE(proc.rootBinder, nullptr);
658 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
659}
660
Steven Moreland4cf688f2021-03-31 01:48:58 +0000661TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000663 ASSERT_NE(proc.rootBinder, nullptr);
664 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
665}
666
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000667TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000668 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669 for (auto session : proc.proc.sessions) {
670 ASSERT_NE(nullptr, session.root);
671 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000672 }
673}
674
Steven Morelandc1635952021-04-01 16:20:47 +0000675TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000676 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000677 Parcel data;
678 Parcel reply;
679 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
680}
681
Steven Moreland67753c32021-04-02 18:45:19 +0000682TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000683 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000684
685 Parcel p1;
686 p1.markForBinder(proc.rootBinder);
687 p1.writeInt32(3);
688
689 Parcel p2;
690
691 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
692 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
693}
694
Steven Morelandc1635952021-04-01 16:20:47 +0000695TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000696 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000697 Parcel data;
698 data.markForBinder(proc.rootBinder);
699 Parcel reply;
700 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
701}
702
Steven Morelandc1635952021-04-01 16:20:47 +0000703TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000704 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000705 EXPECT_OK(proc.rootIface->sendString("asdf"));
706}
707
Steven Morelandc1635952021-04-01 16:20:47 +0000708TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000709 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 std::string doubled;
711 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
712 EXPECT_EQ("cool cool ", doubled);
713}
714
Steven Morelandc1635952021-04-01 16:20:47 +0000715TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000716 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000717 std::string single = std::string(1024, 'a');
718 std::string doubled;
719 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
720 EXPECT_EQ(single + single, doubled);
721}
722
Steven Morelandc1635952021-04-01 16:20:47 +0000723TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000724 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000725
726 int32_t pingResult;
727 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
728 EXPECT_EQ(OK, pingResult);
729
730 EXPECT_EQ(0, MyBinderRpcSession::gNum);
731}
732
Steven Morelandc1635952021-04-01 16:20:47 +0000733TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000734 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000735
736 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
737 sp<IBinder> outBinder;
738 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
739 EXPECT_EQ(inBinder, outBinder);
740
741 wp<IBinder> weak = inBinder;
742 inBinder = nullptr;
743 outBinder = nullptr;
744
745 // Force reading a reply, to process any pending dec refs from the other
746 // process (the other process will process dec refs there before processing
747 // the ping here).
748 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
749
750 EXPECT_EQ(nullptr, weak.promote());
751
752 EXPECT_EQ(0, MyBinderRpcSession::gNum);
753}
754
Steven Morelandc1635952021-04-01 16:20:47 +0000755TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000756 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000757
758 sp<IBinderRpcSession> session;
759 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
760
761 sp<IBinder> inBinder = IInterface::asBinder(session);
762 sp<IBinder> outBinder;
763 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
764 EXPECT_EQ(inBinder, outBinder);
765
766 wp<IBinder> weak = inBinder;
767 session = nullptr;
768 inBinder = nullptr;
769 outBinder = nullptr;
770
771 // Force reading a reply, to process any pending dec refs from the other
772 // process (the other process will process dec refs there before processing
773 // the ping here).
774 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
775
776 EXPECT_EQ(nullptr, weak.promote());
777}
778
Steven Morelandc1635952021-04-01 16:20:47 +0000779TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000780 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000781
782 sp<IBinder> outBinder;
783 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
784 EXPECT_EQ(nullptr, outBinder);
785}
786
Steven Morelandc1635952021-04-01 16:20:47 +0000787TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000788 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000789
790 IBinder* ptr = nullptr;
791 {
792 sp<IBinder> binder = new BBinder();
793 ptr = binder.get();
794 EXPECT_OK(proc.rootIface->holdBinder(binder));
795 }
796
797 sp<IBinder> held;
798 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
799
800 EXPECT_EQ(held.get(), ptr);
801
802 // stop holding binder, because we test to make sure references are cleaned
803 // up
804 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
805 // and flush ref counts
806 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
807}
808
809// START TESTS FOR LIMITATIONS OF SOCKET BINDER
810// These are behavioral differences form regular binder, where certain usecases
811// aren't supported.
812
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000813TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000814 auto proc1 = createRpcTestSocketServerProcess({});
815 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000816
817 sp<IBinder> outBinder;
818 EXPECT_EQ(INVALID_OPERATION,
819 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
820}
821
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000822TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000823 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000824
825 sp<IBinder> outBinder;
826 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000827 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000828 .transactionError());
829}
830
Steven Morelandc1635952021-04-01 16:20:47 +0000831TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000832 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000833
834 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
835 sp<IBinder> outBinder;
836 EXPECT_EQ(INVALID_OPERATION,
837 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
838}
839
Steven Morelandc1635952021-04-01 16:20:47 +0000840TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000841 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000842
843 // for historical reasons, IServiceManager interface only returns the
844 // exception code
845 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
846 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
847}
848
849// END TESTS FOR LIMITATIONS OF SOCKET BINDER
850
Steven Morelandc1635952021-04-01 16:20:47 +0000851TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000852 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000853
854 sp<IBinder> outBinder;
855 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
856 EXPECT_EQ(proc.rootBinder, outBinder);
857}
858
Steven Morelandc1635952021-04-01 16:20:47 +0000859TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000860 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000861
862 auto nastyNester = sp<MyBinderRpcTest>::make();
863 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
864
865 wp<IBinder> weak = nastyNester;
866 nastyNester = nullptr;
867 EXPECT_EQ(nullptr, weak.promote());
868}
869
Steven Morelandc1635952021-04-01 16:20:47 +0000870TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000871 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000872
873 sp<IBinder> a;
874 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
875
876 sp<IBinder> b;
877 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
878
879 EXPECT_EQ(a, b);
880}
881
Steven Morelandc1635952021-04-01 16:20:47 +0000882TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000883 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000884
885 sp<IBinder> a;
886 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
887 wp<IBinder> weak = a;
888 a = nullptr;
889
890 sp<IBinder> b;
891 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
892
893 // this is the wrong behavior, since BpBinder
894 // doesn't implement onIncStrongAttempted
895 // but make sure there is no crash
896 EXPECT_EQ(nullptr, weak.promote());
897
898 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
899
900 // In order to fix this:
901 // - need to have incStrongAttempted reflected across IPC boundary (wait for
902 // response to promote - round trip...)
903 // - sendOnLastWeakRef, to delete entries out of RpcState table
904 EXPECT_EQ(b, weak.promote());
905}
906
907#define expectSessions(expected, iface) \
908 do { \
909 int session; \
910 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
911 EXPECT_EQ(expected, session); \
912 } while (false)
913
Steven Morelandc1635952021-04-01 16:20:47 +0000914TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000915 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
917 sp<IBinderRpcSession> session;
918 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
919 std::string out;
920 EXPECT_OK(session->getName(&out));
921 EXPECT_EQ("aoeu", out);
922
923 expectSessions(1, proc.rootIface);
924 session = nullptr;
925 expectSessions(0, proc.rootIface);
926}
927
Steven Morelandc1635952021-04-01 16:20:47 +0000928TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000929 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000930
931 std::vector<sp<IBinderRpcSession>> sessions;
932
933 for (size_t i = 0; i < 15; i++) {
934 expectSessions(i, proc.rootIface);
935 sp<IBinderRpcSession> session;
936 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
937 sessions.push_back(session);
938 }
939 expectSessions(sessions.size(), proc.rootIface);
940 for (size_t i = 0; i < sessions.size(); i++) {
941 std::string out;
942 EXPECT_OK(sessions.at(i)->getName(&out));
943 EXPECT_EQ(std::to_string(i), out);
944 }
945 expectSessions(sessions.size(), proc.rootIface);
946
947 while (!sessions.empty()) {
948 sessions.pop_back();
949 expectSessions(sessions.size(), proc.rootIface);
950 }
951 expectSessions(0, proc.rootIface);
952}
953
954size_t epochMillis() {
955 using std::chrono::duration_cast;
956 using std::chrono::milliseconds;
957 using std::chrono::seconds;
958 using std::chrono::system_clock;
959 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
960}
961
Steven Morelandc1635952021-04-01 16:20:47 +0000962TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000963 constexpr size_t kNumThreads = 10;
964
Steven Moreland4313d7e2021-07-15 23:41:22 +0000965 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000966
967 EXPECT_OK(proc.rootIface->lock());
968
969 // block all but one thread taking locks
970 std::vector<std::thread> ts;
971 for (size_t i = 0; i < kNumThreads - 1; i++) {
972 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
973 }
974
975 usleep(100000); // give chance for calls on other threads
976
977 // other calls still work
978 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
979
980 constexpr size_t blockTimeMs = 500;
981 size_t epochMsBefore = epochMillis();
982 // after this, we should never see a response within this time
983 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
984
985 // this call should be blocked for blockTimeMs
986 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
987
988 size_t epochMsAfter = epochMillis();
989 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
990
991 for (auto& t : ts) t.join();
992}
993
Steven Morelandc1635952021-04-01 16:20:47 +0000994TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000995 constexpr size_t kNumThreads = 10;
996 constexpr size_t kNumCalls = kNumThreads + 3;
997 constexpr size_t kSleepMs = 500;
998
Steven Moreland4313d7e2021-07-15 23:41:22 +0000999 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001000
1001 size_t epochMsBefore = epochMillis();
1002
1003 std::vector<std::thread> ts;
1004 for (size_t i = 0; i < kNumCalls; i++) {
1005 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
1006 }
1007
1008 for (auto& t : ts) t.join();
1009
1010 size_t epochMsAfter = epochMillis();
1011
1012 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
1013
1014 // Potential flake, but make sure calls are handled in parallel.
1015 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
1016}
1017
Steven Morelandc1635952021-04-01 16:20:47 +00001018TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001019 constexpr size_t kNumClientThreads = 10;
1020 constexpr size_t kNumServerThreads = 10;
1021 constexpr size_t kNumCalls = 100;
1022
Steven Moreland4313d7e2021-07-15 23:41:22 +00001023 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001024
1025 std::vector<std::thread> threads;
1026 for (size_t i = 0; i < kNumClientThreads; i++) {
1027 threads.push_back(std::thread([&] {
1028 for (size_t j = 0; j < kNumCalls; j++) {
1029 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001030 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001031 EXPECT_EQ(proc.rootBinder, out);
1032 }
1033 }));
1034 }
1035
1036 for (auto& t : threads) t.join();
1037}
1038
Steven Morelandc6046982021-04-20 00:49:42 +00001039TEST_P(BinderRpc, OnewayStressTest) {
1040 constexpr size_t kNumClientThreads = 10;
1041 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +00001042 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +00001043
Steven Moreland4313d7e2021-07-15 23:41:22 +00001044 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001045
1046 std::vector<std::thread> threads;
1047 for (size_t i = 0; i < kNumClientThreads; i++) {
1048 threads.push_back(std::thread([&] {
1049 for (size_t j = 0; j < kNumCalls; j++) {
1050 EXPECT_OK(proc.rootIface->sendString("a"));
1051 }
1052
1053 // check threads are not stuck
1054 EXPECT_OK(proc.rootIface->sleepMs(250));
1055 }));
1056 }
1057
1058 for (auto& t : threads) t.join();
1059}
1060
Steven Morelandc1635952021-04-01 16:20:47 +00001061TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001062 constexpr size_t kReallyLongTimeMs = 100;
1063 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1064
Steven Moreland4313d7e2021-07-15 23:41:22 +00001065 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001066
1067 size_t epochMsBefore = epochMillis();
1068
1069 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1070
1071 size_t epochMsAfter = epochMillis();
1072 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1073}
1074
Steven Morelandc1635952021-04-01 16:20:47 +00001075TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001076 constexpr size_t kNumSleeps = 10;
1077 constexpr size_t kNumExtraServerThreads = 4;
1078 constexpr size_t kSleepMs = 50;
1079
1080 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001081 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001082
1083 EXPECT_OK(proc.rootIface->lock());
1084
1085 for (size_t i = 0; i < kNumSleeps; i++) {
1086 // these should be processed serially
1087 proc.rootIface->sleepMsAsync(kSleepMs);
1088 }
1089 // should also be processesed serially
1090 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1091
1092 size_t epochMsBefore = epochMillis();
1093 EXPECT_OK(proc.rootIface->lockUnlock());
1094 size_t epochMsAfter = epochMillis();
1095
1096 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001097
1098 // pending oneway transactions hold ref, make sure we read data on all
1099 // sockets
1100 std::vector<std::thread> threads;
1101 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1102 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1103 }
1104 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001105}
1106
Steven Morelandd45be622021-06-04 02:19:37 +00001107TEST_P(BinderRpc, OnewayCallExhaustion) {
1108 constexpr size_t kNumClients = 2;
1109 constexpr size_t kTooLongMs = 1000;
1110
Steven Moreland4313d7e2021-07-15 23:41:22 +00001111 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001112
1113 // Build up oneway calls on the second session to make sure it terminates
1114 // and shuts down. The first session should be unaffected (proc destructor
1115 // checks the first session).
1116 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1117
1118 std::vector<std::thread> threads;
1119 for (size_t i = 0; i < kNumClients; i++) {
1120 // one of these threads will get stuck queueing a transaction once the
1121 // socket fills up, the other will be able to fill up transactions on
1122 // this object
1123 threads.push_back(std::thread([&] {
1124 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1125 }
1126 }));
1127 }
1128 for (auto& t : threads) t.join();
1129
1130 Status status = iface->sleepMsAsync(kTooLongMs);
1131 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1132
Steven Moreland798e0d12021-07-14 23:19:25 +00001133 // now that it has died, wait for the remote session to shutdown
1134 std::vector<int32_t> remoteCounts;
1135 do {
1136 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1137 } while (remoteCounts.size() == kNumClients);
1138
Steven Morelandd45be622021-06-04 02:19:37 +00001139 // the second session should be shutdown in the other process by the time we
1140 // are able to join above (it'll only be hung up once it finishes processing
1141 // any pending commands). We need to erase this session from the record
1142 // here, so that the destructor for our session won't check that this
1143 // session is valid, but we still want it to test the other session.
1144 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1145}
1146
Steven Moreland659416d2021-05-11 00:47:50 +00001147TEST_P(BinderRpc, Callbacks) {
1148 const static std::string kTestString = "good afternoon!";
1149
Steven Morelandc7d40132021-06-10 03:42:11 +00001150 for (bool callIsOneway : {true, false}) {
1151 for (bool callbackIsOneway : {true, false}) {
1152 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001153 auto proc = createRpcTestSocketServerProcess(
1154 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001155 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001156
Steven Morelandc7d40132021-06-10 03:42:11 +00001157 if (callIsOneway) {
1158 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1159 kTestString));
1160 } else {
1161 EXPECT_OK(
1162 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1163 }
Steven Moreland659416d2021-05-11 00:47:50 +00001164
Steven Morelandc7d40132021-06-10 03:42:11 +00001165 using std::literals::chrono_literals::operator""s;
1166 std::unique_lock<std::mutex> _l(cb->mMutex);
1167 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001168
Steven Morelandc7d40132021-06-10 03:42:11 +00001169 EXPECT_EQ(cb->mValues.size(), 1)
1170 << "callIsOneway: " << callIsOneway
1171 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1172 if (cb->mValues.empty()) continue;
1173 EXPECT_EQ(cb->mValues.at(0), kTestString)
1174 << "callIsOneway: " << callIsOneway
1175 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001176
Steven Morelandc7d40132021-06-10 03:42:11 +00001177 // since we are severing the connection, we need to go ahead and
1178 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001179 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1180 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1181 }
Steven Moreland659416d2021-05-11 00:47:50 +00001182
Steven Moreland1b304292021-07-15 22:59:34 +00001183 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001184 // need to manually shut it down
1185 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001186
Steven Morelandc7d40132021-06-10 03:42:11 +00001187 proc.expectAlreadyShutdown = true;
1188 }
Steven Moreland659416d2021-05-11 00:47:50 +00001189 }
1190 }
1191}
1192
Steven Moreland195edb82021-06-08 02:44:39 +00001193TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001194 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001195 auto cb = sp<MyBinderRpcCallback>::make();
1196
1197 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1198 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1199}
1200
Steven Morelandc1635952021-04-01 16:20:47 +00001201TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001202 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001203 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001204
1205 // make sure there is some state during crash
1206 // 1. we hold their binder
1207 sp<IBinderRpcSession> session;
1208 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1209 // 2. they hold our binder
1210 sp<IBinder> binder = new BBinder();
1211 EXPECT_OK(proc.rootIface->holdBinder(binder));
1212
1213 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1214 << "Do death cleanup: " << doDeathCleanup;
1215
Steven Morelandaf4ca712021-05-24 23:22:08 +00001216 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001217 }
1218}
1219
Steven Morelandd7302072021-05-15 01:32:04 +00001220TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001221 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001222
1223 // we can't allocate IPCThreadState so actually the first time should
1224 // succeed :(
1225 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1226
1227 // second time! we catch the error :)
1228 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1229
Steven Morelandaf4ca712021-05-24 23:22:08 +00001230 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001231}
1232
Steven Moreland37aff182021-03-26 02:04:16 +00001233TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001234 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001235
1236 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1237 ASSERT_NE(binder, nullptr);
1238
1239 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1240}
1241
1242TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
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 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1249 ASSERT_NE(ndkBinder, nullptr);
1250
1251 std::string out;
1252 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1253 ASSERT_TRUE(status.isOk()) << status.getDescription();
1254 ASSERT_EQ("aoeuaoeu", out);
1255}
1256
Steven Moreland5553ac42020-11-11 02:14:45 +00001257ssize_t countFds() {
1258 DIR* dir = opendir("/proc/self/fd/");
1259 if (dir == nullptr) return -1;
1260 ssize_t ret = 0;
1261 dirent* ent;
1262 while ((ent = readdir(dir)) != nullptr) ret++;
1263 closedir(dir);
1264 return ret;
1265}
1266
Steven Morelandc1635952021-04-01 16:20:47 +00001267TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001268 ssize_t beforeFds = countFds();
1269 ASSERT_GE(beforeFds, 0);
1270 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001271 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001272 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1273 }
1274 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1275}
1276
Steven Morelandda573042021-06-12 01:13:45 +00001277static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001278 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001279 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001280 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001281 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001282 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1283 if (status == -EAFNOSUPPORT) {
1284 return false;
1285 }
1286 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1287 }
Steven Morelandda573042021-06-12 01:13:45 +00001288 server->start();
1289
Yifan Hongfdd9f692021-09-09 15:12:52 -07001290 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001291 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001292 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001293 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1294 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001295}
1296
Yifan Hong1deca4b2021-09-10 16:16:44 -07001297static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1298 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1299
1300 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001301
1302 static bool hasVsockLoopback = testSupportVsockLoopback();
1303
1304 if (hasVsockLoopback) {
1305 ret.push_back(SocketType::VSOCK);
1306 }
1307
1308 return ret;
1309}
1310
Yifan Hong702115c2021-06-24 15:39:18 -07001311INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1312 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1313 ::testing::ValuesIn(RpcSecurityValues())),
1314 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001315
Yifan Hong702115c2021-06-24 15:39:18 -07001316class BinderRpcServerRootObject
1317 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001318
1319TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1320 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1321 auto setRootObject = [](bool isStrong) -> SetFn {
1322 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1323 };
1324
Yifan Hong702115c2021-06-24 15:39:18 -07001325 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1326 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001327 auto binder1 = sp<BBinder>::make();
1328 IBinder* binderRaw1 = binder1.get();
1329 setRootObject(isStrong1)(server.get(), binder1);
1330 EXPECT_EQ(binderRaw1, server->getRootObject());
1331 binder1.clear();
1332 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1333
1334 auto binder2 = sp<BBinder>::make();
1335 IBinder* binderRaw2 = binder2.get();
1336 setRootObject(isStrong2)(server.get(), binder2);
1337 EXPECT_EQ(binderRaw2, server->getRootObject());
1338 binder2.clear();
1339 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1340}
1341
1342INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001343 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1344 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001345
Yifan Hong1a235852021-05-13 16:07:47 -07001346class OneOffSignal {
1347public:
1348 // If notify() was previously called, or is called within |duration|, return true; else false.
1349 template <typename R, typename P>
1350 bool wait(std::chrono::duration<R, P> duration) {
1351 std::unique_lock<std::mutex> lock(mMutex);
1352 return mCv.wait_for(lock, duration, [this] { return mValue; });
1353 }
1354 void notify() {
1355 std::unique_lock<std::mutex> lock(mMutex);
1356 mValue = true;
1357 lock.unlock();
1358 mCv.notify_all();
1359 }
1360
1361private:
1362 std::mutex mMutex;
1363 std::condition_variable mCv;
1364 bool mValue = false;
1365};
1366
Yifan Hong702115c2021-06-24 15:39:18 -07001367TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001368 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001369 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001370 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001371 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001372 auto joinEnds = std::make_shared<OneOffSignal>();
1373
1374 // If things are broken and the thread never stops, don't block other tests. Because the thread
1375 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1376 // shared pointers are passed.
1377 std::thread([server, joinEnds] {
1378 server->join();
1379 joinEnds->notify();
1380 }).detach();
1381
1382 bool shutdown = false;
1383 for (int i = 0; i < 10 && !shutdown; i++) {
1384 usleep(300 * 1000); // 300ms; total 3s
1385 if (server->shutdown()) shutdown = true;
1386 }
1387 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1388
1389 ASSERT_TRUE(joinEnds->wait(2s))
1390 << "After server->shutdown() returns true, join() did not stop after 2s";
1391}
1392
Yifan Hong194acf22021-06-29 18:44:56 -07001393TEST(BinderRpc, Java) {
1394#if !defined(__ANDROID__)
1395 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1396 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1397 "to binderHostDeviceTest. Hence, just disable this test on host.";
1398#endif // !__ANDROID__
1399 sp<IServiceManager> sm = defaultServiceManager();
1400 ASSERT_NE(nullptr, sm);
1401 // Any Java service with non-empty getInterfaceDescriptor() would do.
1402 // Let's pick batteryproperties.
1403 auto binder = sm->checkService(String16("batteryproperties"));
1404 ASSERT_NE(nullptr, binder);
1405 auto descriptor = binder->getInterfaceDescriptor();
1406 ASSERT_GE(descriptor.size(), 0);
1407 ASSERT_EQ(OK, binder->pingBinder());
1408
1409 auto rpcServer = RpcServer::make();
1410 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1411 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001412 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001413 auto socket = rpcServer->releaseServer();
1414
1415 auto keepAlive = sp<BBinder>::make();
1416 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1417
1418 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001419 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001420 auto rpcBinder = rpcSession->getRootObject();
1421 ASSERT_NE(nullptr, rpcBinder);
1422
1423 ASSERT_EQ(OK, rpcBinder->pingBinder());
1424
1425 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1426 << "getInterfaceDescriptor should not crash system_server";
1427 ASSERT_EQ(OK, rpcBinder->pingBinder());
1428}
1429
Yifan Hong702115c2021-06-24 15:39:18 -07001430INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1431 BinderRpcSimple::PrintTestParam);
1432
Yifan Hong1deca4b2021-09-10 16:16:44 -07001433class RpcTransportTest
Yifan Hong22211f82021-09-14 12:32:25 -07001434 : public ::testing::TestWithParam<
1435 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>> {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001436public:
1437 using ConnectToServer = std::function<base::unique_fd()>;
1438 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1439 auto [socketType, rpcSecurity, certificateFormat] = info.param;
Yifan Hong22211f82021-09-14 12:32:25 -07001440 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1441 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1442 return ret;
1443 }
1444 static std::vector<ParamType> getRpcTranportTestParams() {
1445 std::vector<RpcTransportTest::ParamType> ret;
1446 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1447 for (auto rpcSecurity : RpcSecurityValues()) {
1448 switch (rpcSecurity) {
1449 case RpcSecurity::RAW: {
1450 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1451 } break;
1452 case RpcSecurity::TLS: {
1453 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1454 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1455 } break;
1456 }
1457 }
1458 }
1459 return ret;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001460 }
1461 void TearDown() override {
Yifan Honge07d2732021-09-13 21:59:14 -07001462 for (auto& server : mServers) server->shutdownAndWait();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001463 }
1464
1465 // A server that handles client socket connections.
1466 class Server {
1467 public:
1468 explicit Server() {}
1469 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001470 ~Server() { shutdownAndWait(); }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001471 [[nodiscard]] AssertionResult setUp() {
1472 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1473 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1474 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1475 switch (socketType) {
1476 case SocketType::PRECONNECTED: {
1477 return AssertionFailure() << "Not supported by this test";
1478 } break;
1479 case SocketType::UNIX: {
1480 auto addr = allocateSocketAddress();
1481 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1482 if (status != OK) {
1483 return AssertionFailure()
1484 << "setupUnixDomainServer: " << statusToString(status);
1485 }
1486 mConnectToServer = [addr] {
1487 return connectTo(UnixSocketAddress(addr.c_str()));
1488 };
1489 } break;
1490 case SocketType::VSOCK: {
1491 auto port = allocateVsockPort();
1492 auto status = rpcServer->setupVsockServer(port);
1493 if (status != OK) {
1494 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1495 }
1496 mConnectToServer = [port] {
1497 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1498 };
1499 } break;
1500 case SocketType::INET: {
1501 unsigned int port;
1502 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1503 if (status != OK) {
1504 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1505 }
1506 mConnectToServer = [port] {
1507 const char* addr = kLocalInetAddress;
1508 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1509 if (aiStart == nullptr) return base::unique_fd{};
1510 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1511 auto fd = connectTo(
1512 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1513 if (fd.ok()) return fd;
1514 }
1515 ALOGE("None of the socket address resolved for %s:%u can be connected",
1516 addr, port);
1517 return base::unique_fd{};
1518 };
1519 }
1520 }
1521 mFd = rpcServer->releaseServer();
1522 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
1523 mCtx = newFactory(rpcSecurity, mCertVerifier)->newServerCtx();
1524 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1525 mSetup = true;
1526 return AssertionSuccess();
1527 }
1528 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1529 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1530 return mCertVerifier;
1531 }
1532 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1533 void start() {
1534 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1535 mThread = std::make_unique<std::thread>(&Server::run, this);
1536 }
1537 void run() {
1538 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1539
1540 std::vector<std::thread> threads;
1541 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1542 base::unique_fd acceptedFd(
1543 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1544 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1545 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1546 }
1547
1548 for (auto& thread : threads) thread.join();
1549 }
1550 void handleOne(android::base::unique_fd acceptedFd) {
1551 ASSERT_TRUE(acceptedFd.ok());
1552 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1553 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001554 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001555 }
Yifan Honge07d2732021-09-13 21:59:14 -07001556 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001557 shutdown();
1558 join();
1559 }
1560 void shutdown() { mFdTrigger->trigger(); }
1561
1562 void setPostConnect(
1563 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1564 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001565 }
1566
1567 private:
1568 std::unique_ptr<std::thread> mThread;
1569 ConnectToServer mConnectToServer;
1570 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1571 base::unique_fd mFd;
1572 std::unique_ptr<RpcTransportCtx> mCtx;
1573 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1574 std::make_shared<RpcCertificateVerifierSimple>();
1575 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001576 // The function invoked after connection and handshake. By default, it is
1577 // |defaultPostConnect| that sends |kMessage| to the client.
1578 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1579 Server::defaultPostConnect;
1580
1581 void join() {
1582 if (mThread != nullptr) {
1583 mThread->join();
1584 mThread = nullptr;
1585 }
1586 }
1587
1588 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1589 FdTrigger* fdTrigger) {
1590 std::string message(kMessage);
1591 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1592 message.size());
1593 if (status != OK) return AssertionFailure() << statusToString(status);
1594 return AssertionSuccess();
1595 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001596 };
1597
1598 class Client {
1599 public:
1600 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1601 Client(Client&&) = default;
1602 [[nodiscard]] AssertionResult setUp() {
1603 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001604 mFdTrigger = FdTrigger::make();
1605 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1606 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1607 return AssertionSuccess();
1608 }
1609 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1610 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1611 return mCertVerifier;
1612 }
Yifan Hong67519322021-09-13 18:51:16 -07001613 // connect() and do handshake
1614 bool setUpTransport() {
1615 mFd = mConnectToServer();
1616 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1617 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1618 return mClientTransport != nullptr;
1619 }
1620 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1621 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1622 std::string readMessage(expectedMessage.size(), '\0');
1623 status_t readStatus =
1624 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
1625 readMessage.size());
1626 if (readStatus != OK) {
1627 return AssertionFailure() << statusToString(readStatus);
1628 }
1629 if (readMessage != expectedMessage) {
1630 return AssertionFailure()
1631 << "Expected " << expectedMessage << ", actual " << readMessage;
1632 }
1633 return AssertionSuccess();
1634 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001635 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001636 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1638 return;
1639 }
1640 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001641 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 }
1643
1644 private:
1645 ConnectToServer mConnectToServer;
1646 base::unique_fd mFd;
1647 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1648 std::unique_ptr<RpcTransportCtx> mCtx;
1649 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1650 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001651 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001652 };
1653
1654 // Make A trust B.
1655 template <typename A, typename B>
1656 status_t trust(A* a, B* b) {
1657 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1658 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001659 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1660 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1661 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001662 }
1663
1664 static constexpr const char* kMessage = "hello";
1665 std::vector<std::unique_ptr<Server>> mServers;
1666};
1667
1668TEST_P(RpcTransportTest, GoodCertificate) {
1669 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1670 ASSERT_TRUE(server->setUp());
1671
1672 Client client(server->getConnectToServerFn());
1673 ASSERT_TRUE(client.setUp());
1674
1675 ASSERT_EQ(OK, trust(&client, server));
1676 ASSERT_EQ(OK, trust(server, &client));
1677
1678 server->start();
1679 client.run();
1680}
1681
1682TEST_P(RpcTransportTest, MultipleClients) {
1683 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1684 ASSERT_TRUE(server->setUp());
1685
1686 std::vector<Client> clients;
1687 for (int i = 0; i < 2; i++) {
1688 auto& client = clients.emplace_back(server->getConnectToServerFn());
1689 ASSERT_TRUE(client.setUp());
1690 ASSERT_EQ(OK, trust(&client, server));
1691 ASSERT_EQ(OK, trust(server, &client));
1692 }
1693
1694 server->start();
1695 for (auto& client : clients) client.run();
1696}
1697
1698TEST_P(RpcTransportTest, UntrustedServer) {
1699 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1700
1701 auto untrustedServer = mServers.emplace_back(std::make_unique<Server>()).get();
1702 ASSERT_TRUE(untrustedServer->setUp());
1703
1704 Client client(untrustedServer->getConnectToServerFn());
1705 ASSERT_TRUE(client.setUp());
1706
1707 ASSERT_EQ(OK, trust(untrustedServer, &client));
1708
1709 untrustedServer->start();
1710
1711 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1712 // the client can't verify the server's identity.
1713 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1714 client.run(handshakeOk);
1715}
1716TEST_P(RpcTransportTest, MaliciousServer) {
1717 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1718 auto validServer = mServers.emplace_back(std::make_unique<Server>()).get();
1719 ASSERT_TRUE(validServer->setUp());
1720
1721 auto maliciousServer = mServers.emplace_back(std::make_unique<Server>()).get();
1722 ASSERT_TRUE(maliciousServer->setUp());
1723
1724 Client client(maliciousServer->getConnectToServerFn());
1725 ASSERT_TRUE(client.setUp());
1726
1727 ASSERT_EQ(OK, trust(&client, validServer));
1728 ASSERT_EQ(OK, trust(validServer, &client));
1729 ASSERT_EQ(OK, trust(maliciousServer, &client));
1730
1731 maliciousServer->start();
1732
1733 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1734 // the client can't verify the server's identity.
1735 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1736 client.run(handshakeOk);
1737}
1738
1739TEST_P(RpcTransportTest, UntrustedClient) {
1740 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1741 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1742 ASSERT_TRUE(server->setUp());
1743
1744 Client client(server->getConnectToServerFn());
1745 ASSERT_TRUE(client.setUp());
1746
1747 ASSERT_EQ(OK, trust(&client, server));
1748
1749 server->start();
1750
1751 // For TLS, Client should be able to verify server's identity, so client should see
1752 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1753 // identity and should drop the connection, so client shouldn't be able to read anything.
1754 bool readOk = rpcSecurity != RpcSecurity::TLS;
1755 client.run(true, readOk);
1756}
1757
1758TEST_P(RpcTransportTest, MaliciousClient) {
1759 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1760 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1761 ASSERT_TRUE(server->setUp());
1762
1763 Client validClient(server->getConnectToServerFn());
1764 ASSERT_TRUE(validClient.setUp());
1765 Client maliciousClient(server->getConnectToServerFn());
1766 ASSERT_TRUE(maliciousClient.setUp());
1767
1768 ASSERT_EQ(OK, trust(&validClient, server));
1769 ASSERT_EQ(OK, trust(&maliciousClient, server));
1770
1771 server->start();
1772
1773 // See UntrustedClient.
1774 bool readOk = rpcSecurity != RpcSecurity::TLS;
1775 maliciousClient.run(true, readOk);
1776}
1777
Yifan Hong67519322021-09-13 18:51:16 -07001778TEST_P(RpcTransportTest, Trigger) {
1779 std::string msg2 = ", world!";
1780 std::mutex writeMutex;
1781 std::condition_variable writeCv;
1782 bool shouldContinueWriting = false;
1783 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1784 std::string message(kMessage);
1785 auto status =
1786 serverTransport->interruptableWriteFully(fdTrigger, message.data(), message.size());
1787 if (status != OK) return AssertionFailure() << statusToString(status);
1788
1789 {
1790 std::unique_lock<std::mutex> lock(writeMutex);
1791 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1792 return AssertionFailure() << "write barrier not cleared in time!";
1793 }
1794 }
1795
1796 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size());
Steven Morelandc591b472021-09-16 13:56:11 -07001797 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001798 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001799 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001800 << statusToString(status);
1801 return AssertionSuccess();
1802 };
1803
1804 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1805 ASSERT_TRUE(server->setUp());
1806
1807 // Set up client
1808 Client client(server->getConnectToServerFn());
1809 ASSERT_TRUE(client.setUp());
1810
1811 // Exchange keys
1812 ASSERT_EQ(OK, trust(&client, server));
1813 ASSERT_EQ(OK, trust(server, &client));
1814
1815 server->setPostConnect(serverPostConnect);
1816
Yifan Hong67519322021-09-13 18:51:16 -07001817 server->start();
1818 // connect() to server and do handshake
1819 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001820 // read the first message. This ensures that server has finished handshake and start handling
1821 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hong67519322021-09-13 18:51:16 -07001822 ASSERT_TRUE(client.readMessage(kMessage));
1823 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1824 // write is on an FdTrigger that has been shut down.
1825 server->shutdown();
1826 // Continues server thread to write the second message.
1827 {
Yifan Hong22211f82021-09-14 12:32:25 -07001828 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001829 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001830 }
Yifan Hong22211f82021-09-14 12:32:25 -07001831 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001832 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001833 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001834 // On the client side, second read fails with DEAD_OBJECT
1835 ASSERT_FALSE(client.readMessage(msg2));
1836}
1837
Yifan Hong1deca4b2021-09-10 16:16:44 -07001838INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001839 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001840 RpcTransportTest::PrintParamInfo);
1841
Steven Morelandc1635952021-04-01 16:20:47 +00001842} // namespace android
1843
1844int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001845 ::testing::InitGoogleTest(&argc, argv);
1846 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1847 return RUN_ALL_TESTS();
1848}