xref: /aosp_15_r20/frameworks/native/libs/binder/servicedispatcher.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright (C) 2021 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 #include <sysexits.h>
18 #include <unistd.h>
19 
20 #include <filesystem>
21 #include <iostream>
22 
23 #include <android-base/logging.h>
24 #include <android-base/properties.h>
25 #include <android/debug/BnAdbCallback.h>
26 #include <android/debug/IAdbManager.h>
27 #include <android/os/BnServiceManager.h>
28 #include <android/os/IServiceManager.h>
29 #include <binder/IServiceManager.h>
30 #include <binder/ProcessState.h>
31 #include <binder/RpcServer.h>
32 
33 #include "file.h"
34 
35 using android::BBinder;
36 using android::defaultServiceManager;
37 using android::OK;
38 using android::RpcServer;
39 using android::sp;
40 using android::status_t;
41 using android::statusToString;
42 using android::String16;
43 using android::base::GetBoolProperty;
44 using android::base::InitLogging;
45 using android::base::LogdLogger;
46 using android::base::LogId;
47 using android::base::LogSeverity;
48 using android::base::StdioLogger;
49 using std::string_view_literals::operator""sv;
50 
51 namespace {
52 
53 const char* kLocalInetAddress = "127.0.0.1";
54 using ServiceRetriever = decltype(&android::IServiceManager::checkService);
55 using android::debug::IAdbManager;
56 
Usage(std::filesystem::path program)57 int Usage(std::filesystem::path program) {
58     auto basename = program.filename();
59     // clang-format off
60     LOG(ERROR) << R"(dispatch calls to RPC service.
61 Usage:
62   )" << basename << R"( [-g] [-i <ip_address>] <service_name>
63     <service_name>: the service to connect to.
64   )" << basename << R"( [-g] manager
65     Runs an RPC-friendly service that redirects calls to servicemanager.
66 
67   -g: use getService() instead of checkService().
68   -i: use ip_address when setting up the server instead of '127.0.0.1'
69 
70   If successful, writes port number and a new line character to stdout, and
71   blocks until killed.
72   Otherwise, writes error message to stderr and exits with non-zero code.
73 )";
74     // clang-format on
75     return EX_USAGE;
76 }
77 
Dispatch(const char * name,const ServiceRetriever & serviceRetriever,const char * ip_address=kLocalInetAddress)78 int Dispatch(const char* name, const ServiceRetriever& serviceRetriever,
79              const char* ip_address = kLocalInetAddress) {
80     auto sm = defaultServiceManager();
81     if (nullptr == sm) {
82         LOG(ERROR) << "No servicemanager";
83         return EX_SOFTWARE;
84     }
85     auto binder = std::invoke(serviceRetriever, defaultServiceManager(), String16(name));
86     if (nullptr == binder) {
87         LOG(ERROR) << "No service \"" << name << "\"";
88         return EX_SOFTWARE;
89     }
90     auto rpcServer = RpcServer::make();
91     if (nullptr == rpcServer) {
92         LOG(ERROR) << "Cannot create RpcServer";
93         return EX_SOFTWARE;
94     }
95     unsigned int port;
96     if (status_t status = rpcServer->setupInetServer(ip_address, 0, &port); status != OK) {
97         LOG(ERROR) << "setupInetServer failed: " << statusToString(status);
98         return EX_SOFTWARE;
99     }
100     auto socket = rpcServer->releaseServer();
101     auto keepAliveBinder = sp<BBinder>::make();
102     auto status = binder->setRpcClientDebug(std::move(socket), keepAliveBinder);
103     if (status != OK) {
104         LOG(ERROR) << "setRpcClientDebug failed with " << statusToString(status);
105         return EX_SOFTWARE;
106     }
107     LOG(INFO) << "Finish setting up RPC on service " << name << " on port " << port;
108 
109     std::cout << port << std::endl;
110 
111     TEMP_FAILURE_RETRY(pause());
112 
113     PLOG(FATAL) << "TEMP_FAILURE_RETRY(pause()) exits; this should not happen!";
114     __builtin_unreachable();
115 }
116 
117 // Wrapper that wraps a BpServiceManager as a BnServiceManager.
118 class ServiceManagerProxyToNative : public android::os::BnServiceManager {
119 public:
ServiceManagerProxyToNative(const sp<android::os::IServiceManager> & impl)120     ServiceManagerProxyToNative(const sp<android::os::IServiceManager>& impl) : mImpl(impl) {}
getService(const std::string &,android::sp<android::IBinder> *)121     android::binder::Status getService(const std::string&,
122                                        android::sp<android::IBinder>*) override {
123         // We can't send BpBinder for regular binder over RPC.
124         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
125     }
getService2(const std::string &,android::os::Service *)126     android::binder::Status getService2(const std::string&, android::os::Service*) override {
127         // We can't send BpBinder for regular binder over RPC.
128         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
129     }
checkService(const std::string &,android::os::Service *)130     android::binder::Status checkService(const std::string&, android::os::Service*) override {
131         // We can't send BpBinder for regular binder over RPC.
132         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
133     }
addService(const std::string &,const android::sp<android::IBinder> &,bool,int32_t)134     android::binder::Status addService(const std::string&, const android::sp<android::IBinder>&,
135                                        bool, int32_t) override {
136         // We can't send BpBinder for RPC over regular binder.
137         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
138     }
listServices(int32_t dumpPriority,std::vector<std::string> * _aidl_return)139     android::binder::Status listServices(int32_t dumpPriority,
140                                          std::vector<std::string>* _aidl_return) override {
141         return mImpl->listServices(dumpPriority, _aidl_return);
142     }
registerForNotifications(const std::string &,const android::sp<android::os::IServiceCallback> &)143     android::binder::Status registerForNotifications(
144             const std::string&, const android::sp<android::os::IServiceCallback>&) override {
145         // We can't send BpBinder for RPC over regular binder.
146         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
147     }
unregisterForNotifications(const std::string &,const android::sp<android::os::IServiceCallback> &)148     android::binder::Status unregisterForNotifications(
149             const std::string&, const android::sp<android::os::IServiceCallback>&) override {
150         // We can't send BpBinder for RPC over regular binder.
151         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
152     }
isDeclared(const std::string & name,bool * _aidl_return)153     android::binder::Status isDeclared(const std::string& name, bool* _aidl_return) override {
154         return mImpl->isDeclared(name, _aidl_return);
155     }
getDeclaredInstances(const std::string & iface,std::vector<std::string> * _aidl_return)156     android::binder::Status getDeclaredInstances(const std::string& iface,
157                                                  std::vector<std::string>* _aidl_return) override {
158         return mImpl->getDeclaredInstances(iface, _aidl_return);
159     }
updatableViaApex(const std::string & name,std::optional<std::string> * _aidl_return)160     android::binder::Status updatableViaApex(const std::string& name,
161                                              std::optional<std::string>* _aidl_return) override {
162         return mImpl->updatableViaApex(name, _aidl_return);
163     }
getUpdatableNames(const std::string & apexName,std::vector<std::string> * _aidl_return)164     android::binder::Status getUpdatableNames(const std::string& apexName,
165                                               std::vector<std::string>* _aidl_return) override {
166         return mImpl->getUpdatableNames(apexName, _aidl_return);
167     }
getConnectionInfo(const std::string & name,std::optional<android::os::ConnectionInfo> * _aidl_return)168     android::binder::Status getConnectionInfo(
169             const std::string& name,
170             std::optional<android::os::ConnectionInfo>* _aidl_return) override {
171         return mImpl->getConnectionInfo(name, _aidl_return);
172     }
registerClientCallback(const std::string &,const android::sp<android::IBinder> &,const android::sp<android::os::IClientCallback> &)173     android::binder::Status registerClientCallback(
174             const std::string&, const android::sp<android::IBinder>&,
175             const android::sp<android::os::IClientCallback>&) override {
176         // We can't send BpBinder for RPC over regular binder.
177         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
178     }
tryUnregisterService(const std::string &,const android::sp<android::IBinder> &)179     android::binder::Status tryUnregisterService(const std::string&,
180                                                  const android::sp<android::IBinder>&) override {
181         // We can't send BpBinder for RPC over regular binder.
182         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
183     }
getServiceDebugInfo(std::vector<android::os::ServiceDebugInfo> * _aidl_return)184     android::binder::Status getServiceDebugInfo(
185             std::vector<android::os::ServiceDebugInfo>* _aidl_return) override {
186         return mImpl->getServiceDebugInfo(_aidl_return);
187     }
188 
189 private:
190     sp<android::os::IServiceManager> mImpl;
191 };
192 
193 // Workaround for b/191059588.
194 // TODO(b/191059588): Once we can run RpcServer on single-threaded services,
195 //   `servicedispatcher manager` should call Dispatch("manager") directly.
wrapServiceManager(const ServiceRetriever & serviceRetriever,const char * ip_address=kLocalInetAddress)196 int wrapServiceManager(const ServiceRetriever& serviceRetriever,
197                        const char* ip_address = kLocalInetAddress) {
198     auto sm = defaultServiceManager();
199     if (nullptr == sm) {
200         LOG(ERROR) << "No servicemanager";
201         return EX_SOFTWARE;
202     }
203     auto service = std::invoke(serviceRetriever, defaultServiceManager(), String16("manager"));
204     if (nullptr == service) {
205         LOG(ERROR) << "No service called `manager`";
206         return EX_SOFTWARE;
207     }
208     auto interface = android::os::IServiceManager::asInterface(service);
209     if (nullptr == interface) {
210         LOG(ERROR) << "Cannot cast service called `manager` to IServiceManager";
211         return EX_SOFTWARE;
212     }
213 
214     // Work around restriction that doesn't allow us to send proxy over RPC.
215     interface = sp<ServiceManagerProxyToNative>::make(interface);
216     service = ServiceManagerProxyToNative::asBinder(interface);
217 
218     auto rpcServer = RpcServer::make();
219     rpcServer->setRootObject(service);
220     unsigned int port;
221     if (status_t status = rpcServer->setupInetServer(ip_address, 0, &port); status != OK) {
222         LOG(ERROR) << "Unable to set up inet server: " << statusToString(status);
223         return EX_SOFTWARE;
224     }
225     LOG(INFO) << "Finish wrapping servicemanager with RPC on port " << port;
226     std::cout << port << std::endl;
227     rpcServer->join();
228 
229     LOG(FATAL) << "Wrapped servicemanager exits; this should not happen!";
230     __builtin_unreachable();
231 }
232 
233 class AdbCallback : public android::debug::BnAdbCallback {
234 public:
onDebuggingChanged(bool enabled,android::debug::AdbTransportType)235     android::binder::Status onDebuggingChanged(bool enabled,
236                                                android::debug::AdbTransportType) override {
237         if (!enabled) {
238             LOG(ERROR) << "ADB debugging disabled, exiting.";
239             exit(EX_SOFTWARE);
240         }
241         return android::binder::Status::ok();
242     }
243 };
244 
exitOnAdbDebuggingDisabled()245 void exitOnAdbDebuggingDisabled() {
246     auto adb = android::waitForService<IAdbManager>(String16("adb"));
247     CHECK(adb != nullptr) << "Unable to retrieve service adb";
248     auto status = adb->registerCallback(sp<AdbCallback>::make());
249     CHECK(status.isOk()) << "Unable to call IAdbManager::registerCallback: " << status;
250 }
251 
252 // Log to logd. For warning and more severe messages, also log to stderr.
253 class ServiceDispatcherLogger {
254 public:
operator ()(LogId id,LogSeverity severity,const char * tag,const char * file,unsigned int line,const char * message)255     void operator()(LogId id, LogSeverity severity, const char* tag, const char* file,
256                     unsigned int line, const char* message) {
257         mLogdLogger(id, severity, tag, file, line, message);
258         if (severity >= LogSeverity::WARNING) {
259             std::cout << std::flush;
260             auto progname = std::filesystem::path(getprogname()).filename();
261             std::cerr << progname << ": " << message << std::endl;
262         }
263     }
264 
265 private:
266     LogdLogger mLogdLogger{};
267 };
268 
269 } // namespace
270 
main(int argc,char * argv[])271 int main(int argc, char* argv[]) {
272     InitLogging(argv, ServiceDispatcherLogger());
273 
274     if (!GetBoolProperty("ro.debuggable", false)) {
275         LOG(ERROR) << "servicedispatcher is only allowed on debuggable builds.";
276         return EX_NOPERM;
277     }
278     LOG(WARNING) << "WARNING: servicedispatcher is debug only. Use with caution.";
279 
280     int opt;
281     ServiceRetriever serviceRetriever = &android::IServiceManager::checkService;
282     char* ip_address = nullptr;
283     while (-1 != (opt = getopt(argc, argv, "gi:"))) {
284         switch (opt) {
285             case 'g': {
286 #pragma clang diagnostic push
287 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
288                 serviceRetriever = &android::IServiceManager::getService;
289 #pragma clang diagnostic pop
290             } break;
291             case 'i': {
292                 ip_address = optarg;
293             } break;
294             default: {
295                 return Usage(argv[0]);
296             }
297         }
298     }
299 
300     android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
301     android::ProcessState::self()->startThreadPool();
302     exitOnAdbDebuggingDisabled();
303 
304     if (optind + 1 != argc) return Usage(argv[0]);
305     auto name = argv[optind];
306 
307     if (name == "manager"sv) {
308         if (ip_address) {
309             return wrapServiceManager(serviceRetriever, ip_address);
310         } else {
311             return wrapServiceManager(serviceRetriever);
312         }
313     }
314     if (ip_address) {
315         return Dispatch(name, serviceRetriever, ip_address);
316     } else {
317         return Dispatch(name, serviceRetriever);
318     }
319 }
320