blob: 262d7e4570a6e298e919ce70227cd37711b9d3bf [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>
Andrei Homescu9d8adb12022-08-02 04:38:30 +000025#include <android-base/stringprintf.h>
26#include <binder/Binder.h>
27#include <binder/BpBinder.h>
28#include <binder/IPCThreadState.h>
29#include <binder/IServiceManager.h>
30#include <binder/RpcServer.h>
31#include <binder/RpcSession.h>
32#include <binder/RpcThreads.h>
33#include <binder/RpcTransport.h>
34#include <binder/RpcTransportRaw.h>
35#include <unistd.h>
36#include <cinttypes>
37#include <string>
38#include <vector>
39
40#ifndef __TRUSTY__
Andrei Homescu2a298012022-06-15 01:08:54 +000041#include <android-base/file.h>
42#include <android-base/logging.h>
43#include <android-base/properties.h>
44#include <android/binder_auto_utils.h>
45#include <android/binder_libbinder.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000046#include <binder/ProcessState.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000047#include <binder/RpcTlsTestUtils.h>
48#include <binder/RpcTlsUtils.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000049#include <binder/RpcTransportTls.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000050
51#include <signal.h>
52
David Brazdil21c887c2022-09-23 12:25:18 +010053#include "../OS.h" // for testing UnixBootstrap clients
Andrei Homescu2a298012022-06-15 01:08:54 +000054#include "../RpcSocketAddress.h" // for testing preconnected clients
Andrei Homescu2a298012022-06-15 01:08:54 +000055#include "../vm_sockets.h" // for VMADDR_*
Andrei Homescu9d8adb12022-08-02 04:38:30 +000056#endif // __TRUSTY__
57
58#include "../BuildFlags.h"
59#include "../FdTrigger.h"
60#include "../RpcState.h" // for debugging
Andrei Homescu2a298012022-06-15 01:08:54 +000061#include "utils/Errors.h"
62
63namespace android {
64
65constexpr char kLocalInetAddress[] = "127.0.0.1";
66
67enum class RpcSecurity { RAW, TLS };
68
69static inline std::vector<RpcSecurity> RpcSecurityValues() {
70 return {RpcSecurity::RAW, RpcSecurity::TLS};
71}
72
Andrei Homescu9d8adb12022-08-02 04:38:30 +000073static inline std::vector<uint32_t> testVersions() {
74 std::vector<uint32_t> versions;
75 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
76 versions.push_back(i);
77 }
78 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
79 return versions;
80}
81
82static inline std::string trustyIpcPort(uint32_t serverVersion) {
83 return base::StringPrintf("com.android.trusty.binderRpcTestService.V%" PRIu32, serverVersion);
84}
85
Andrei Homescu2a298012022-06-15 01:08:54 +000086enum class SocketType {
87 PRECONNECTED,
88 UNIX,
David Brazdil21c887c2022-09-23 12:25:18 +010089 UNIX_BOOTSTRAP,
Alice Wang893a9912022-10-24 10:44:09 +000090 UNIX_RAW,
Andrei Homescu2a298012022-06-15 01:08:54 +000091 VSOCK,
92 INET,
93};
David Brazdil21c887c2022-09-23 12:25:18 +010094
Andrei Homescu2a298012022-06-15 01:08:54 +000095static inline std::string PrintToString(SocketType socketType) {
96 switch (socketType) {
97 case SocketType::PRECONNECTED:
98 return "preconnected_uds";
99 case SocketType::UNIX:
100 return "unix_domain_socket";
David Brazdil21c887c2022-09-23 12:25:18 +0100101 case SocketType::UNIX_BOOTSTRAP:
102 return "unix_domain_socket_bootstrap";
Alice Wang893a9912022-10-24 10:44:09 +0000103 case SocketType::UNIX_RAW:
104 return "raw_uds";
Andrei Homescu2a298012022-06-15 01:08:54 +0000105 case SocketType::VSOCK:
106 return "vm_socket";
107 case SocketType::INET:
108 return "inet_socket";
109 default:
110 LOG_ALWAYS_FATAL("Unknown socket type");
111 return "";
112 }
113}
114
Andrei Homescu9a9b1b42022-10-14 01:40:59 +0000115static inline size_t epochMillis() {
116 using std::chrono::duration_cast;
117 using std::chrono::milliseconds;
118 using std::chrono::seconds;
119 using std::chrono::system_clock;
120 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
121}
122
Andrei Homescu2a298012022-06-15 01:08:54 +0000123struct BinderRpcOptions {
124 size_t numThreads = 1;
125 size_t numSessions = 1;
126 size_t numIncomingConnections = 0;
127 size_t numOutgoingConnections = SIZE_MAX;
128 RpcSession::FileDescriptorTransportMode clientFileDescriptorTransportMode =
129 RpcSession::FileDescriptorTransportMode::NONE;
130 std::vector<RpcSession::FileDescriptorTransportMode>
131 serverSupportedFileDescriptorTransportModes = {
132 RpcSession::FileDescriptorTransportMode::NONE};
133
134 // If true, connection failures will result in `ProcessSession::sessions` being empty
135 // instead of a fatal error.
136 bool allowConnectFailure = false;
137};
138
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000139#ifndef __TRUSTY__
Andrei Homescu2a298012022-06-15 01:08:54 +0000140static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
141 uint64_t length = str.length();
142 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
143 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
144}
145
146static inline std::string readString(android::base::borrowed_fd fd) {
147 uint64_t length;
148 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
149 std::string ret(length, '\0');
150 CHECK(android::base::ReadFully(fd, ret.data(), length));
151 return ret;
152}
153
154static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
155 Parcel parcel;
156 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
157 writeString(fd, std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
158}
159
160template <typename T>
161static inline T readFromFd(android::base::borrowed_fd fd) {
162 std::string data = readString(fd);
163 Parcel parcel;
164 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
165 T object;
166 CHECK_EQ(OK, object.readFromParcel(&parcel));
167 return object;
168}
169
170static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
171 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
172 std::unique_ptr<RpcAuth> auth = nullptr) {
173 switch (rpcSecurity) {
174 case RpcSecurity::RAW:
175 return RpcTransportCtxFactoryRaw::make();
176 case RpcSecurity::TLS: {
177 if (verifier == nullptr) {
178 verifier = std::make_shared<RpcCertificateVerifierSimple>();
179 }
180 if (auth == nullptr) {
181 auth = std::make_unique<RpcAuthSelfSigned>();
182 }
183 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
184 }
185 default:
186 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
187 }
188}
189
190// Create an FD that returns `contents` when read.
191static inline base::unique_fd mockFileDescriptor(std::string contents) {
192 android::base::unique_fd readFd, writeFd;
193 CHECK(android::base::Pipe(&readFd, &writeFd)) << strerror(errno);
194 RpcMaybeThread([writeFd = std::move(writeFd), contents = std::move(contents)]() {
195 signal(SIGPIPE, SIG_IGN); // ignore possible SIGPIPE from the write
196 if (!WriteStringToFd(contents, writeFd)) {
197 int savedErrno = errno;
198 LOG_ALWAYS_FATAL_IF(EPIPE != savedErrno, "mockFileDescriptor write failed: %s",
199 strerror(savedErrno));
200 }
201 }).detach();
202 return readFd;
203}
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000204#endif // __TRUSTY__
Andrei Homescu2a298012022-06-15 01:08:54 +0000205
Frederick Mayleb0221d12022-10-03 23:10:53 +0000206// A threadsafe channel where writes block until the value is read.
207template <typename T>
208class HandoffChannel {
209public:
210 void write(T v) {
211 {
212 RpcMutexUniqueLock lock(mMutex);
213 // Wait for space to send.
214 mCvEmpty.wait(lock, [&]() { return !mValue.has_value(); });
215 mValue.emplace(std::move(v));
216 }
217 mCvFull.notify_all();
218 RpcMutexUniqueLock lock(mMutex);
219 // Wait for it to be taken.
220 mCvEmpty.wait(lock, [&]() { return !mValue.has_value(); });
221 }
222
223 T read() {
224 RpcMutexUniqueLock lock(mMutex);
225 if (!mValue.has_value()) {
226 mCvFull.wait(lock, [&]() { return mValue.has_value(); });
227 }
228 T v = std::move(mValue.value());
229 mValue.reset();
230 lock.unlock();
231 mCvEmpty.notify_all();
232 return std::move(v);
233 }
234
235private:
236 RpcMutex mMutex;
237 RpcConditionVariable mCvEmpty;
238 RpcConditionVariable mCvFull;
239 std::optional<T> mValue;
240};
241
Andrei Homescu2a298012022-06-15 01:08:54 +0000242using android::binder::Status;
243
244class MyBinderRpcSession : public BnBinderRpcSession {
245public:
246 static std::atomic<int32_t> gNum;
247
248 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
249 Status getName(std::string* name) override {
250 *name = mName;
251 return Status::ok();
252 }
253 ~MyBinderRpcSession() { gNum--; }
254
255private:
256 std::string mName;
257};
258
259class MyBinderRpcCallback : public BnBinderRpcCallback {
260 Status sendCallback(const std::string& value) {
261 RpcMutexUniqueLock _l(mMutex);
262 mValues.push_back(value);
263 _l.unlock();
264 mCv.notify_one();
265 return Status::ok();
266 }
267 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
268
269public:
270 RpcMutex mMutex;
271 RpcConditionVariable mCv;
272 std::vector<std::string> mValues;
273};
274
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000275// Base class for all concrete implementations of MyBinderRpcTest.
276// Sub-classes that want to provide a full implementation should derive
277// from this class instead of MyBinderRpcTestDefault below so the compiler
278// checks that all methods are implemented.
279class MyBinderRpcTestBase : public BnBinderRpcTest {
Andrei Homescu2a298012022-06-15 01:08:54 +0000280public:
Andrei Homescu2a298012022-06-15 01:08:54 +0000281 int port = 0;
282
283 Status sendString(const std::string& str) override {
284 (void)str;
285 return Status::ok();
286 }
287 Status doubleString(const std::string& str, std::string* strstr) override {
288 *strstr = str + str;
289 return Status::ok();
290 }
291 Status getClientPort(int* out) override {
292 *out = port;
293 return Status::ok();
294 }
Andrei Homescu2a298012022-06-15 01:08:54 +0000295 Status getNullBinder(sp<IBinder>* out) override {
296 out->clear();
297 return Status::ok();
298 }
299 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
300 if (binder == nullptr) {
301 std::cout << "Received null binder!" << std::endl;
302 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
303 }
304 *out = binder->pingBinder();
305 return Status::ok();
306 }
307 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
308 *out = binder;
309 return Status::ok();
310 }
311 static sp<IBinder> mHeldBinder;
312 Status holdBinder(const sp<IBinder>& binder) override {
313 mHeldBinder = binder;
314 return Status::ok();
315 }
316 Status getHeldBinder(sp<IBinder>* held) override {
317 *held = mHeldBinder;
318 return Status::ok();
319 }
320 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
321 if (count <= 0) return Status::ok();
322 return binder->nestMe(this, count - 1);
323 }
324 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
325 static sp<IBinder> binder = new BBinder;
326 *out = binder;
327 return Status::ok();
328 }
329 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
330 *out = new MyBinderRpcSession(name);
331 return Status::ok();
332 }
333 Status getNumOpenSessions(int32_t* out) override {
334 *out = MyBinderRpcSession::gNum;
335 return Status::ok();
336 }
337
338 RpcMutex blockMutex;
339 Status lock() override {
340 blockMutex.lock();
341 return Status::ok();
342 }
343 Status unlockInMsAsync(int32_t ms) override {
344 usleep(ms * 1000);
345 blockMutex.unlock();
346 return Status::ok();
347 }
348 Status lockUnlock() override {
349 RpcMutexLockGuard _l(blockMutex);
350 return Status::ok();
351 }
352
353 Status sleepMs(int32_t ms) override {
354 usleep(ms * 1000);
355 return Status::ok();
356 }
357
358 Status sleepMsAsync(int32_t ms) override {
359 // In-process binder calls are asynchronous, but the call to this method
360 // is synchronous wrt its client. This in/out-process threading model
361 // diffentiation is a classic binder leaky abstraction (for better or
362 // worse) and is preserved here the way binder sockets plugs itself
363 // into BpBinder, as nothing is changed at the higher levels
364 // (IInterface) which result in this behavior.
365 return sleepMs(ms);
366 }
367
368 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
369 const std::string& value) override {
370 if (callback == nullptr) {
371 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
372 }
373
374 if (delayed) {
375 RpcMaybeThread([=]() {
376 ALOGE("Executing delayed callback: '%s'", value.c_str());
377 Status status = doCallback(callback, oneway, false, value);
378 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
379 }).detach();
380 return Status::ok();
381 }
382
383 if (oneway) {
384 return callback->sendOnewayCallback(value);
385 }
386
387 return callback->sendCallback(value);
388 }
389
390 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
391 const std::string& value) override {
392 return doCallback(callback, oneway, delayed, value);
393 }
394
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000395protected:
396 // Generic version of countBinders that works with both
397 // RpcServer and RpcServerTrusty
398 template <typename T>
399 Status countBindersImpl(const wp<T>& server, std::vector<int32_t>* out) {
400 sp<T> spServer = server.promote();
401 if (spServer == nullptr) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000402 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
403 }
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000404 out->clear();
405 for (auto session : spServer->listSessions()) {
406 size_t count = session->state()->countBinders();
407 out->push_back(count);
Andrei Homescu2a298012022-06-15 01:08:54 +0000408 }
409 return Status::ok();
410 }
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000411};
Andrei Homescu2a298012022-06-15 01:08:54 +0000412
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000413// Default implementation of MyBinderRpcTest that can be used as-is
414// or derived from by classes that only want to implement a subset of
415// the unimplemented methods
416class MyBinderRpcTestDefault : public MyBinderRpcTestBase {
417public:
418 Status countBinders(std::vector<int32_t>* /*out*/) override {
419 return Status::fromStatusT(UNKNOWN_TRANSACTION);
Andrei Homescu2a298012022-06-15 01:08:54 +0000420 }
421
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000422 Status die(bool /*cleanup*/) override { return Status::fromStatusT(UNKNOWN_TRANSACTION); }
423
424 Status scheduleShutdown() override { return Status::fromStatusT(UNKNOWN_TRANSACTION); }
425
426 Status useKernelBinderCallingId() override { return Status::fromStatusT(UNKNOWN_TRANSACTION); }
427
428 Status echoAsFile(const std::string& /*content*/,
429 android::os::ParcelFileDescriptor* /*out*/) override {
430 return Status::fromStatusT(UNKNOWN_TRANSACTION);
Andrei Homescu2a298012022-06-15 01:08:54 +0000431 }
Frederick Mayleb0221d12022-10-03 23:10:53 +0000432
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000433 Status concatFiles(const std::vector<android::os::ParcelFileDescriptor>& /*files*/,
434 android::os::ParcelFileDescriptor* /*out*/) override {
435 return Status::fromStatusT(UNKNOWN_TRANSACTION);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000436 }
437
Andrei Homescu9d8adb12022-08-02 04:38:30 +0000438 Status blockingSendFdOneway(const android::os::ParcelFileDescriptor& /*fd*/) override {
439 return Status::fromStatusT(UNKNOWN_TRANSACTION);
440 }
441
442 Status blockingRecvFd(android::os::ParcelFileDescriptor* /*fd*/) override {
443 return Status::fromStatusT(UNKNOWN_TRANSACTION);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000444 }
Andrei Homescu2a298012022-06-15 01:08:54 +0000445};
446
447} // namespace android