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