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