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     }
checkService(const std::string &,android::sp<android::IBinder> *)126     android::binder::Status checkService(const std::string&,
127                                          android::sp<android::IBinder>*) override {
128         // We can't send BpBinder for regular binder over RPC.
129         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
130     }
addService(const std::string &,const android::sp<android::IBinder> &,bool,int32_t)131     android::binder::Status addService(const std::string&, const android::sp<android::IBinder>&,
132                                        bool, int32_t) override {
133         // We can't send BpBinder for RPC over regular binder.
134         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
135     }
listServices(int32_t dumpPriority,std::vector<std::string> * _aidl_return)136     android::binder::Status listServices(int32_t dumpPriority,
137                                          std::vector<std::string>* _aidl_return) override {
138         return mImpl->listServices(dumpPriority, _aidl_return);
139     }
registerForNotifications(const std::string &,const android::sp<android::os::IServiceCallback> &)140     android::binder::Status registerForNotifications(
141             const std::string&, const android::sp<android::os::IServiceCallback>&) override {
142         // We can't send BpBinder for RPC over regular binder.
143         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
144     }
unregisterForNotifications(const std::string &,const android::sp<android::os::IServiceCallback> &)145     android::binder::Status unregisterForNotifications(
146             const std::string&, const android::sp<android::os::IServiceCallback>&) override {
147         // We can't send BpBinder for RPC over regular binder.
148         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
149     }
isDeclared(const std::string & name,bool * _aidl_return)150     android::binder::Status isDeclared(const std::string& name, bool* _aidl_return) override {
151         return mImpl->isDeclared(name, _aidl_return);
152     }
getDeclaredInstances(const std::string & iface,std::vector<std::string> * _aidl_return)153     android::binder::Status getDeclaredInstances(const std::string& iface,
154                                                  std::vector<std::string>* _aidl_return) override {
155         return mImpl->getDeclaredInstances(iface, _aidl_return);
156     }
updatableViaApex(const std::string & name,std::optional<std::string> * _aidl_return)157     android::binder::Status updatableViaApex(const std::string& name,
158                                              std::optional<std::string>* _aidl_return) override {
159         return mImpl->updatableViaApex(name, _aidl_return);
160     }
getUpdatableNames(const std::string & apexName,std::vector<std::string> * _aidl_return)161     android::binder::Status getUpdatableNames(const std::string& apexName,
162                                               std::vector<std::string>* _aidl_return) override {
163         return mImpl->getUpdatableNames(apexName, _aidl_return);
164     }
getConnectionInfo(const std::string & name,std::optional<android::os::ConnectionInfo> * _aidl_return)165     android::binder::Status getConnectionInfo(
166             const std::string& name,
167             std::optional<android::os::ConnectionInfo>* _aidl_return) override {
168         return mImpl->getConnectionInfo(name, _aidl_return);
169     }
registerClientCallback(const std::string &,const android::sp<android::IBinder> &,const android::sp<android::os::IClientCallback> &)170     android::binder::Status registerClientCallback(
171             const std::string&, const android::sp<android::IBinder>&,
172             const android::sp<android::os::IClientCallback>&) override {
173         // We can't send BpBinder for RPC over regular binder.
174         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
175     }
tryUnregisterService(const std::string &,const android::sp<android::IBinder> &)176     android::binder::Status tryUnregisterService(const std::string&,
177                                                  const android::sp<android::IBinder>&) override {
178         // We can't send BpBinder for RPC over regular binder.
179         return android::binder::Status::fromStatusT(android::INVALID_OPERATION);
180     }
getServiceDebugInfo(std::vector<android::os::ServiceDebugInfo> * _aidl_return)181     android::binder::Status getServiceDebugInfo(
182             std::vector<android::os::ServiceDebugInfo>* _aidl_return) override {
183         return mImpl->getServiceDebugInfo(_aidl_return);
184     }
185 
186 private:
187     sp<android::os::IServiceManager> mImpl;
188 };
189 
190 // Workaround for b/191059588.
191 // TODO(b/191059588): Once we can run RpcServer on single-threaded services,
192 //   `servicedispatcher manager` should call Dispatch("manager") directly.
wrapServiceManager(const ServiceRetriever & serviceRetriever,const char * ip_address=kLocalInetAddress)193 int wrapServiceManager(const ServiceRetriever& serviceRetriever,
194                        const char* ip_address = kLocalInetAddress) {
195     auto sm = defaultServiceManager();
196     if (nullptr == sm) {
197         LOG(ERROR) << "No servicemanager";
198         return EX_SOFTWARE;
199     }
200     auto service = std::invoke(serviceRetriever, defaultServiceManager(), String16("manager"));
201     if (nullptr == service) {
202         LOG(ERROR) << "No service called `manager`";
203         return EX_SOFTWARE;
204     }
205     auto interface = android::os::IServiceManager::asInterface(service);
206     if (nullptr == interface) {
207         LOG(ERROR) << "Cannot cast service called `manager` to IServiceManager";
208         return EX_SOFTWARE;
209     }
210 
211     // Work around restriction that doesn't allow us to send proxy over RPC.
212     interface = sp<ServiceManagerProxyToNative>::make(interface);
213     service = ServiceManagerProxyToNative::asBinder(interface);
214 
215     auto rpcServer = RpcServer::make();
216     rpcServer->setRootObject(service);
217     unsigned int port;
218     if (status_t status = rpcServer->setupInetServer(ip_address, 0, &port); status != OK) {
219         LOG(ERROR) << "Unable to set up inet server: " << statusToString(status);
220         return EX_SOFTWARE;
221     }
222     LOG(INFO) << "Finish wrapping servicemanager with RPC on port " << port;
223     std::cout << port << std::endl;
224     rpcServer->join();
225 
226     LOG(FATAL) << "Wrapped servicemanager exits; this should not happen!";
227     __builtin_unreachable();
228 }
229 
230 class AdbCallback : public android::debug::BnAdbCallback {
231 public:
onDebuggingChanged(bool enabled,android::debug::AdbTransportType)232     android::binder::Status onDebuggingChanged(bool enabled,
233                                                android::debug::AdbTransportType) override {
234         if (!enabled) {
235             LOG(ERROR) << "ADB debugging disabled, exiting.";
236             exit(EX_SOFTWARE);
237         }
238         return android::binder::Status::ok();
239     }
240 };
241 
exitOnAdbDebuggingDisabled()242 void exitOnAdbDebuggingDisabled() {
243     auto adb = android::waitForService<IAdbManager>(String16("adb"));
244     CHECK(adb != nullptr) << "Unable to retrieve service adb";
245     auto status = adb->registerCallback(sp<AdbCallback>::make());
246     CHECK(status.isOk()) << "Unable to call IAdbManager::registerCallback: " << status;
247 }
248 
249 // Log to logd. For warning and more severe messages, also log to stderr.
250 class ServiceDispatcherLogger {
251 public:
operator ()(LogId id,LogSeverity severity,const char * tag,const char * file,unsigned int line,const char * message)252     void operator()(LogId id, LogSeverity severity, const char* tag, const char* file,
253                     unsigned int line, const char* message) {
254         mLogdLogger(id, severity, tag, file, line, message);
255         if (severity >= LogSeverity::WARNING) {
256             std::cout << std::flush;
257             auto progname = std::filesystem::path(getprogname()).filename();
258             std::cerr << progname << ": " << message << std::endl;
259         }
260     }
261 
262 private:
263     LogdLogger mLogdLogger{};
264 };
265 
266 } // namespace
267 
main(int argc,char * argv[])268 int main(int argc, char* argv[]) {
269     InitLogging(argv, ServiceDispatcherLogger());
270 
271     if (!GetBoolProperty("ro.debuggable", false)) {
272         LOG(ERROR) << "servicedispatcher is only allowed on debuggable builds.";
273         return EX_NOPERM;
274     }
275     LOG(WARNING) << "WARNING: servicedispatcher is debug only. Use with caution.";
276 
277     int opt;
278     ServiceRetriever serviceRetriever = &android::IServiceManager::checkService;
279     char* ip_address = nullptr;
280     while (-1 != (opt = getopt(argc, argv, "gi:"))) {
281         switch (opt) {
282             case 'g': {
283 #pragma clang diagnostic push
284 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
285                 serviceRetriever = &android::IServiceManager::getService;
286 #pragma clang diagnostic pop
287             } break;
288             case 'i': {
289                 ip_address = optarg;
290             } break;
291             default: {
292                 return Usage(argv[0]);
293             }
294         }
295     }
296 
297     android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
298     android::ProcessState::self()->startThreadPool();
299     exitOnAdbDebuggingDisabled();
300 
301     if (optind + 1 != argc) return Usage(argv[0]);
302     auto name = argv[optind];
303 
304     if (name == "manager"sv) {
305         if (ip_address) {
306             return wrapServiceManager(serviceRetriever, ip_address);
307         } else {
308             return wrapServiceManager(serviceRetriever);
309         }
310     }
311     if (ip_address) {
312         return Dispatch(name, serviceRetriever, ip_address);
313     } else {
314         return Dispatch(name, serviceRetriever);
315     }
316 }
317