blob: 4513d36a658734760fb28e441b91fac50c7a275d [file] [log] [blame]
Andrei Homescu2a298012022-06-15 01:08:54 +00001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <BinderRpcTestClientInfo.h>
20#include <BinderRpcTestServerConfig.h>
21#include <BinderRpcTestServerInfo.h>
22#include <BnBinderRpcCallback.h>
23#include <BnBinderRpcSession.h>
24#include <BnBinderRpcTest.h>
25#include <aidl/IBinderRpcTest.h>
26#include <android-base/file.h>
27#include <android-base/logging.h>
28#include <android-base/properties.h>
29#include <android/binder_auto_utils.h>
30#include <android/binder_libbinder.h>
31#include <binder/Binder.h>
32#include <binder/BpBinder.h>
33#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
35#include <binder/ProcessState.h>
36#include <binder/RpcServer.h>
37#include <binder/RpcSession.h>
38#include <binder/RpcThreads.h>
39#include <binder/RpcTlsTestUtils.h>
40#include <binder/RpcTlsUtils.h>
41#include <binder/RpcTransport.h>
42#include <binder/RpcTransportRaw.h>
43#include <binder/RpcTransportTls.h>
44#include <unistd.h>
45#include <string>
46#include <vector>
47
48#include <signal.h>
49
50#include "../BuildFlags.h"
51#include "../FdTrigger.h"
52#include "../RpcSocketAddress.h" // for testing preconnected clients
53#include "../RpcState.h" // for debugging
54#include "../vm_sockets.h" // for VMADDR_*
55#include "utils/Errors.h"
56
57namespace android {
58
59constexpr char kLocalInetAddress[] = "127.0.0.1";
60
61enum class RpcSecurity { RAW, TLS };
62
63static inline std::vector<RpcSecurity> RpcSecurityValues() {
64 return {RpcSecurity::RAW, RpcSecurity::TLS};
65}
66
67enum class SocketType {
68 PRECONNECTED,
69 UNIX,
70 VSOCK,
71 INET,
72};
73static inline std::string PrintToString(SocketType socketType) {
74 switch (socketType) {
75 case SocketType::PRECONNECTED:
76 return "preconnected_uds";
77 case SocketType::UNIX:
78 return "unix_domain_socket";
79 case SocketType::VSOCK:
80 return "vm_socket";
81 case SocketType::INET:
82 return "inet_socket";
83 default:
84 LOG_ALWAYS_FATAL("Unknown socket type");
85 return "";
86 }
87}
88
89struct BinderRpcOptions {
90 size_t numThreads = 1;
91 size_t numSessions = 1;
92 size_t numIncomingConnections = 0;
93 size_t numOutgoingConnections = SIZE_MAX;
94 RpcSession::FileDescriptorTransportMode clientFileDescriptorTransportMode =
95 RpcSession::FileDescriptorTransportMode::NONE;
96 std::vector<RpcSession::FileDescriptorTransportMode>
97 serverSupportedFileDescriptorTransportModes = {
98 RpcSession::FileDescriptorTransportMode::NONE};
99
100 // If true, connection failures will result in `ProcessSession::sessions` being empty
101 // instead of a fatal error.
102 bool allowConnectFailure = false;
103};
104
105static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
106 uint64_t length = str.length();
107 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
108 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
109}
110
111static inline std::string readString(android::base::borrowed_fd fd) {
112 uint64_t length;
113 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
114 std::string ret(length, '\0');
115 CHECK(android::base::ReadFully(fd, ret.data(), length));
116 return ret;
117}
118
119static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
120 Parcel parcel;
121 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
122 writeString(fd, std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
123}
124
125template <typename T>
126static inline T readFromFd(android::base::borrowed_fd fd) {
127 std::string data = readString(fd);
128 Parcel parcel;
129 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
130 T object;
131 CHECK_EQ(OK, object.readFromParcel(&parcel));
132 return object;
133}
134
135static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
136 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
137 std::unique_ptr<RpcAuth> auth = nullptr) {
138 switch (rpcSecurity) {
139 case RpcSecurity::RAW:
140 return RpcTransportCtxFactoryRaw::make();
141 case RpcSecurity::TLS: {
142 if (verifier == nullptr) {
143 verifier = std::make_shared<RpcCertificateVerifierSimple>();
144 }
145 if (auth == nullptr) {
146 auth = std::make_unique<RpcAuthSelfSigned>();
147 }
148 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
149 }
150 default:
151 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
152 }
153}
154
155// Create an FD that returns `contents` when read.
156static inline base::unique_fd mockFileDescriptor(std::string contents) {
157 android::base::unique_fd readFd, writeFd;
158 CHECK(android::base::Pipe(&readFd, &writeFd)) << strerror(errno);
159 RpcMaybeThread([writeFd = std::move(writeFd), contents = std::move(contents)]() {
160 signal(SIGPIPE, SIG_IGN); // ignore possible SIGPIPE from the write
161 if (!WriteStringToFd(contents, writeFd)) {
162 int savedErrno = errno;
163 LOG_ALWAYS_FATAL_IF(EPIPE != savedErrno, "mockFileDescriptor write failed: %s",
164 strerror(savedErrno));
165 }
166 }).detach();
167 return readFd;
168}
169
170using android::binder::Status;
171
172class MyBinderRpcSession : public BnBinderRpcSession {
173public:
174 static std::atomic<int32_t> gNum;
175
176 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
177 Status getName(std::string* name) override {
178 *name = mName;
179 return Status::ok();
180 }
181 ~MyBinderRpcSession() { gNum--; }
182
183private:
184 std::string mName;
185};
186
187class MyBinderRpcCallback : public BnBinderRpcCallback {
188 Status sendCallback(const std::string& value) {
189 RpcMutexUniqueLock _l(mMutex);
190 mValues.push_back(value);
191 _l.unlock();
192 mCv.notify_one();
193 return Status::ok();
194 }
195 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
196
197public:
198 RpcMutex mMutex;
199 RpcConditionVariable mCv;
200 std::vector<std::string> mValues;
201};
202
203class MyBinderRpcTest : public BnBinderRpcTest {
204public:
205 wp<RpcServer> server;
206 int port = 0;
207
208 Status sendString(const std::string& str) override {
209 (void)str;
210 return Status::ok();
211 }
212 Status doubleString(const std::string& str, std::string* strstr) override {
213 *strstr = str + str;
214 return Status::ok();
215 }
216 Status getClientPort(int* out) override {
217 *out = port;
218 return Status::ok();
219 }
220 Status countBinders(std::vector<int32_t>* out) override {
221 sp<RpcServer> spServer = server.promote();
222 if (spServer == nullptr) {
223 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
224 }
225 out->clear();
226 for (auto session : spServer->listSessions()) {
227 size_t count = session->state()->countBinders();
228 out->push_back(count);
229 }
230 return Status::ok();
231 }
232 Status getNullBinder(sp<IBinder>* out) override {
233 out->clear();
234 return Status::ok();
235 }
236 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
237 if (binder == nullptr) {
238 std::cout << "Received null binder!" << std::endl;
239 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
240 }
241 *out = binder->pingBinder();
242 return Status::ok();
243 }
244 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
245 *out = binder;
246 return Status::ok();
247 }
248 static sp<IBinder> mHeldBinder;
249 Status holdBinder(const sp<IBinder>& binder) override {
250 mHeldBinder = binder;
251 return Status::ok();
252 }
253 Status getHeldBinder(sp<IBinder>* held) override {
254 *held = mHeldBinder;
255 return Status::ok();
256 }
257 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
258 if (count <= 0) return Status::ok();
259 return binder->nestMe(this, count - 1);
260 }
261 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
262 static sp<IBinder> binder = new BBinder;
263 *out = binder;
264 return Status::ok();
265 }
266 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
267 *out = new MyBinderRpcSession(name);
268 return Status::ok();
269 }
270 Status getNumOpenSessions(int32_t* out) override {
271 *out = MyBinderRpcSession::gNum;
272 return Status::ok();
273 }
274
275 RpcMutex blockMutex;
276 Status lock() override {
277 blockMutex.lock();
278 return Status::ok();
279 }
280 Status unlockInMsAsync(int32_t ms) override {
281 usleep(ms * 1000);
282 blockMutex.unlock();
283 return Status::ok();
284 }
285 Status lockUnlock() override {
286 RpcMutexLockGuard _l(blockMutex);
287 return Status::ok();
288 }
289
290 Status sleepMs(int32_t ms) override {
291 usleep(ms * 1000);
292 return Status::ok();
293 }
294
295 Status sleepMsAsync(int32_t ms) override {
296 // In-process binder calls are asynchronous, but the call to this method
297 // is synchronous wrt its client. This in/out-process threading model
298 // diffentiation is a classic binder leaky abstraction (for better or
299 // worse) and is preserved here the way binder sockets plugs itself
300 // into BpBinder, as nothing is changed at the higher levels
301 // (IInterface) which result in this behavior.
302 return sleepMs(ms);
303 }
304
305 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
306 const std::string& value) override {
307 if (callback == nullptr) {
308 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
309 }
310
311 if (delayed) {
312 RpcMaybeThread([=]() {
313 ALOGE("Executing delayed callback: '%s'", value.c_str());
314 Status status = doCallback(callback, oneway, false, value);
315 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
316 }).detach();
317 return Status::ok();
318 }
319
320 if (oneway) {
321 return callback->sendOnewayCallback(value);
322 }
323
324 return callback->sendCallback(value);
325 }
326
327 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
328 const std::string& value) override {
329 return doCallback(callback, oneway, delayed, value);
330 }
331
332 Status die(bool cleanup) override {
333 if (cleanup) {
334 exit(1);
335 } else {
336 _exit(1);
337 }
338 }
339
340 Status scheduleShutdown() override {
341 sp<RpcServer> strongServer = server.promote();
342 if (strongServer == nullptr) {
343 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
344 }
345 RpcMaybeThread([=] {
346 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
347 }).detach();
348 return Status::ok();
349 }
350
351 Status useKernelBinderCallingId() override {
352 // this is WRONG! It does not make sense when using RPC binder, and
353 // because it is SO wrong, and so much code calls this, it should abort!
354
355 if constexpr (kEnableKernelIpc) {
356 (void)IPCThreadState::self()->getCallingPid();
357 }
358 return Status::ok();
359 }
360
361 Status echoAsFile(const std::string& content, android::os::ParcelFileDescriptor* out) override {
362 out->reset(mockFileDescriptor(content));
363 return Status::ok();
364 }
365
366 Status concatFiles(const std::vector<android::os::ParcelFileDescriptor>& files,
367 android::os::ParcelFileDescriptor* out) override {
368 std::string acc;
369 for (const auto& file : files) {
370 std::string result;
371 CHECK(android::base::ReadFdToString(file.get(), &result));
372 acc.append(result);
373 }
374 out->reset(mockFileDescriptor(acc));
375 return Status::ok();
376 }
377};
378
379} // namespace android