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