1 /*
2  * Copyright (C) 2005 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 #define LOG_TAG "ServiceManager"
18 
19 #include <binder/IServiceManager.h>
20 
21 #include <inttypes.h>
22 #include <unistd.h>
23 
24 #include <android/os/BnServiceCallback.h>
25 #include <android/os/IServiceManager.h>
26 #include <binder/IPCThreadState.h>
27 #include <binder/Parcel.h>
28 #include <utils/Log.h>
29 #include <utils/String8.h>
30 #include <utils/SystemClock.h>
31 
32 #ifndef __ANDROID_VNDK__
33 #include <binder/IPermissionController.h>
34 #endif
35 
36 #ifdef __ANDROID__
37 #include <cutils/properties.h>
38 #endif
39 
40 #include "Static.h"
41 
42 namespace android {
43 
44 using AidlServiceManager = android::os::IServiceManager;
45 using android::binder::Status;
46 
47 // libbinder's IServiceManager.h can't rely on the values generated by AIDL
48 // because many places use its headers via include_dirs (meaning, without
49 // declaring the dependency in the build system). So, for now, we can just check
50 // the values here.
51 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_CRITICAL == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
52 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_HIGH == IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
53 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_NORMAL == IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
54 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_DEFAULT == IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
55 static_assert(AidlServiceManager::DUMP_FLAG_PRIORITY_ALL == IServiceManager::DUMP_FLAG_PRIORITY_ALL);
56 static_assert(AidlServiceManager::DUMP_FLAG_PROTO == IServiceManager::DUMP_FLAG_PROTO);
57 
getInterfaceDescriptor() const58 const String16& IServiceManager::getInterfaceDescriptor() const {
59     return AidlServiceManager::descriptor;
60 }
IServiceManager()61 IServiceManager::IServiceManager() {}
~IServiceManager()62 IServiceManager::~IServiceManager() {}
63 
64 // From the old libbinder IServiceManager interface to IServiceManager.
65 class ServiceManagerShim : public IServiceManager
66 {
67 public:
68     explicit ServiceManagerShim (const sp<AidlServiceManager>& impl);
69 
70     sp<IBinder> getService(const String16& name) const override;
71     sp<IBinder> checkService(const String16& name) const override;
72     status_t addService(const String16& name, const sp<IBinder>& service,
73                         bool allowIsolated, int dumpsysPriority) override;
74     Vector<String16> listServices(int dumpsysPriority) override;
75     sp<IBinder> waitForService(const String16& name16) override;
76     bool isDeclared(const String16& name) override;
77 
78     // for legacy ABI
getInterfaceDescriptor() const79     const String16& getInterfaceDescriptor() const override {
80         return mTheRealServiceManager->getInterfaceDescriptor();
81     }
onAsBinder()82     IBinder* onAsBinder() override {
83         return IInterface::asBinder(mTheRealServiceManager).get();
84     }
85 private:
86     sp<AidlServiceManager> mTheRealServiceManager;
87 };
88 
89 [[clang::no_destroy]] static std::once_flag gSmOnce;
90 [[clang::no_destroy]] static sp<IServiceManager> gDefaultServiceManager;
91 
defaultServiceManager()92 sp<IServiceManager> defaultServiceManager()
93 {
94     std::call_once(gSmOnce, []() {
95         sp<AidlServiceManager> sm = nullptr;
96         while (sm == nullptr) {
97             sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));
98             if (sm == nullptr) {
99                 ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());
100                 sleep(1);
101             }
102         }
103 
104         gDefaultServiceManager = new ServiceManagerShim(sm);
105     });
106 
107     return gDefaultServiceManager;
108 }
109 
setDefaultServiceManager(const sp<IServiceManager> & sm)110 void setDefaultServiceManager(const sp<IServiceManager>& sm) {
111     bool called = false;
112     std::call_once(gSmOnce, [&]() {
113         gDefaultServiceManager = sm;
114         called = true;
115     });
116 
117     if (!called) {
118         LOG_ALWAYS_FATAL("setDefaultServiceManager() called after defaultServiceManager().");
119     }
120 }
121 
122 #if !defined(__ANDROID_VNDK__) && defined(__ANDROID__)
123 // IPermissionController is not accessible to vendors
124 
checkCallingPermission(const String16 & permission)125 bool checkCallingPermission(const String16& permission)
126 {
127     return checkCallingPermission(permission, nullptr, nullptr);
128 }
129 
130 static String16 _permission("permission");
131 
132 
checkCallingPermission(const String16 & permission,int32_t * outPid,int32_t * outUid)133 bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
134 {
135     IPCThreadState* ipcState = IPCThreadState::self();
136     pid_t pid = ipcState->getCallingPid();
137     uid_t uid = ipcState->getCallingUid();
138     if (outPid) *outPid = pid;
139     if (outUid) *outUid = uid;
140     return checkPermission(permission, pid, uid);
141 }
142 
checkPermission(const String16 & permission,pid_t pid,uid_t uid)143 bool checkPermission(const String16& permission, pid_t pid, uid_t uid)
144 {
145     static Mutex gPermissionControllerLock;
146     static sp<IPermissionController> gPermissionController;
147 
148     sp<IPermissionController> pc;
149     gPermissionControllerLock.lock();
150     pc = gPermissionController;
151     gPermissionControllerLock.unlock();
152 
153     int64_t startTime = 0;
154 
155     while (true) {
156         if (pc != nullptr) {
157             bool res = pc->checkPermission(permission, pid, uid);
158             if (res) {
159                 if (startTime != 0) {
160                     ALOGI("Check passed after %d seconds for %s from uid=%d pid=%d",
161                             (int)((uptimeMillis()-startTime)/1000),
162                             String8(permission).string(), uid, pid);
163                 }
164                 return res;
165             }
166 
167             // Is this a permission failure, or did the controller go away?
168             if (IInterface::asBinder(pc)->isBinderAlive()) {
169                 ALOGW("Permission failure: %s from uid=%d pid=%d",
170                         String8(permission).string(), uid, pid);
171                 return false;
172             }
173 
174             // Object is dead!
175             gPermissionControllerLock.lock();
176             if (gPermissionController == pc) {
177                 gPermissionController = nullptr;
178             }
179             gPermissionControllerLock.unlock();
180         }
181 
182         // Need to retrieve the permission controller.
183         sp<IBinder> binder = defaultServiceManager()->checkService(_permission);
184         if (binder == nullptr) {
185             // Wait for the permission controller to come back...
186             if (startTime == 0) {
187                 startTime = uptimeMillis();
188                 ALOGI("Waiting to check permission %s from uid=%d pid=%d",
189                         String8(permission).string(), uid, pid);
190             }
191             sleep(1);
192         } else {
193             pc = interface_cast<IPermissionController>(binder);
194             // Install the new permission controller, and try again.
195             gPermissionControllerLock.lock();
196             gPermissionController = pc;
197             gPermissionControllerLock.unlock();
198         }
199     }
200 }
201 
202 #endif //__ANDROID_VNDK__
203 
204 // ----------------------------------------------------------------------
205 
ServiceManagerShim(const sp<AidlServiceManager> & impl)206 ServiceManagerShim::ServiceManagerShim(const sp<AidlServiceManager>& impl)
207  : mTheRealServiceManager(impl)
208 {}
209 
210 // This implementation could be simplified and made more efficient by delegating
211 // to waitForService. However, this changes the threading structure in some
212 // cases and could potentially break prebuilts. Once we have higher logistical
213 // complexity, this could be attempted.
getService(const String16 & name) const214 sp<IBinder> ServiceManagerShim::getService(const String16& name) const
215 {
216     static bool gSystemBootCompleted = false;
217 
218     sp<IBinder> svc = checkService(name);
219     if (svc != nullptr) return svc;
220 
221     const bool isVendorService =
222         strcmp(ProcessState::self()->getDriverName().c_str(), "/dev/vndbinder") == 0;
223     const long timeout = 5000;
224     int64_t startTime = uptimeMillis();
225     // Vendor code can't access system properties
226     if (!gSystemBootCompleted && !isVendorService) {
227 #ifdef __ANDROID__
228         char bootCompleted[PROPERTY_VALUE_MAX];
229         property_get("sys.boot_completed", bootCompleted, "0");
230         gSystemBootCompleted = strcmp(bootCompleted, "1") == 0 ? true : false;
231 #else
232         gSystemBootCompleted = true;
233 #endif
234     }
235     // retry interval in millisecond; note that vendor services stay at 100ms
236     const long sleepTime = gSystemBootCompleted ? 1000 : 100;
237 
238     ALOGI("Waiting for service '%s' on '%s'...", String8(name).string(),
239           ProcessState::self()->getDriverName().c_str());
240 
241     int n = 0;
242     while (uptimeMillis() - startTime < timeout) {
243         n++;
244         usleep(1000*sleepTime);
245 
246         sp<IBinder> svc = checkService(name);
247         if (svc != nullptr) {
248             ALOGI("Waiting for service '%s' on '%s' successful after waiting %" PRIi64 "ms",
249                   String8(name).string(), ProcessState::self()->getDriverName().c_str(),
250                   uptimeMillis() - startTime);
251             return svc;
252         }
253     }
254     ALOGW("Service %s didn't start. Returning NULL", String8(name).string());
255     return nullptr;
256 }
257 
checkService(const String16 & name) const258 sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
259 {
260     sp<IBinder> ret;
261     if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
262         return nullptr;
263     }
264     return ret;
265 }
266 
addService(const String16 & name,const sp<IBinder> & service,bool allowIsolated,int dumpsysPriority)267 status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
268                                         bool allowIsolated, int dumpsysPriority)
269 {
270     Status status = mTheRealServiceManager->addService(
271         String8(name).c_str(), service, allowIsolated, dumpsysPriority);
272     return status.exceptionCode();
273 }
274 
listServices(int dumpsysPriority)275 Vector<String16> ServiceManagerShim::listServices(int dumpsysPriority)
276 {
277     std::vector<std::string> ret;
278     if (!mTheRealServiceManager->listServices(dumpsysPriority, &ret).isOk()) {
279         return {};
280     }
281 
282     Vector<String16> res;
283     res.setCapacity(ret.size());
284     for (const std::string& name : ret) {
285         res.push(String16(name.c_str()));
286     }
287     return res;
288 }
289 
waitForService(const String16 & name16)290 sp<IBinder> ServiceManagerShim::waitForService(const String16& name16)
291 {
292     class Waiter : public android::os::BnServiceCallback {
293         Status onRegistration(const std::string& /*name*/,
294                               const sp<IBinder>& binder) override {
295             std::unique_lock<std::mutex> lock(mMutex);
296             mBinder = binder;
297             lock.unlock();
298             // Flushing here helps ensure the service's ref count remains accurate
299             IPCThreadState::self()->flushCommands();
300             mCv.notify_one();
301             return Status::ok();
302         }
303     public:
304         sp<IBinder> mBinder;
305         std::mutex mMutex;
306         std::condition_variable mCv;
307     };
308 
309     // Simple RAII object to ensure a function call immediately before going out of scope
310     class Defer {
311     public:
312         Defer(std::function<void()>&& f) : mF(std::move(f)) {}
313         ~Defer() { mF(); }
314     private:
315         std::function<void()> mF;
316     };
317 
318     const std::string name = String8(name16).c_str();
319 
320     sp<IBinder> out;
321     if (!mTheRealServiceManager->getService(name, &out).isOk()) {
322         return nullptr;
323     }
324     if (out != nullptr) return out;
325 
326     sp<Waiter> waiter = new Waiter;
327     if (!mTheRealServiceManager->registerForNotifications(
328             name, waiter).isOk()) {
329         return nullptr;
330     }
331     Defer unregister ([&] {
332         mTheRealServiceManager->unregisterForNotifications(name, waiter);
333     });
334 
335     while(true) {
336         {
337             // It would be really nice if we could read binder commands on this
338             // thread instead of needing a threadpool to be started, but for
339             // instance, if we call getAndExecuteCommand, it might be the case
340             // that another thread serves the callback, and we never get a
341             // command, so we hang indefinitely.
342             std::unique_lock<std::mutex> lock(waiter->mMutex);
343             using std::literals::chrono_literals::operator""s;
344             waiter->mCv.wait_for(lock, 1s, [&] {
345                 return waiter->mBinder != nullptr;
346             });
347             if (waiter->mBinder != nullptr) return waiter->mBinder;
348         }
349 
350         ALOGW("Waited one second for %s (is service started? are binder threads started and available?)", name.c_str());
351 
352         // Handle race condition for lazy services. Here is what can happen:
353         // - the service dies (not processed by init yet).
354         // - sm processes death notification.
355         // - sm gets getService and calls init to start service.
356         // - init gets the start signal, but the service already appears
357         //   started, so it does nothing.
358         // - init gets death signal, but doesn't know it needs to restart
359         //   the service
360         // - we need to request service again to get it to start
361         if (!mTheRealServiceManager->getService(name, &out).isOk()) {
362             return nullptr;
363         }
364         if (out != nullptr) return out;
365     }
366 }
367 
isDeclared(const String16 & name)368 bool ServiceManagerShim::isDeclared(const String16& name) {
369     bool declared;
370     if (!mTheRealServiceManager->isDeclared(String8(name).c_str(), &declared).isOk()) {
371         return false;
372     }
373     return declared;
374 }
375 
376 } // namespace android
377