• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 "ServiceManager.h"
18 
19 #include <android-base/logging.h>
20 #include <android-base/properties.h>
21 #include <binder/BpBinder.h>
22 #include <binder/IPCThreadState.h>
23 #include <binder/ProcessState.h>
24 #include <binder/Stability.h>
25 #include <cutils/android_filesystem_config.h>
26 #include <cutils/multiuser.h>
27 #include <thread>
28 
29 #ifndef VENDORSERVICEMANAGER
30 #include <vintf/VintfObject.h>
31 #ifdef __ANDROID_RECOVERY__
32 #include <vintf/VintfObjectRecovery.h>
33 #endif // __ANDROID_RECOVERY__
34 #include <vintf/constants.h>
35 #endif  // !VENDORSERVICEMANAGER
36 
37 using ::android::binder::Status;
38 using ::android::internal::Stability;
39 
40 namespace android {
41 
is_multiuser_uid_isolated(uid_t uid)42 bool is_multiuser_uid_isolated(uid_t uid) {
43     uid_t appid = multiuser_get_app_id(uid);
44     return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
45 }
46 
47 #ifndef VENDORSERVICEMANAGER
48 
49 struct ManifestWithDescription {
50     std::shared_ptr<const vintf::HalManifest> manifest;
51     const char* description;
52 };
GetManifestsWithDescription()53 static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
54 #ifdef __ANDROID_RECOVERY__
55     auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
56     if (vintfObject == nullptr) {
57         ALOGE("NULL VintfObjectRecovery!");
58         return {};
59     }
60     return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
61 #else
62     auto vintfObject = vintf::VintfObject::GetInstance();
63     if (vintfObject == nullptr) {
64         ALOGE("NULL VintfObject!");
65         return {};
66     }
67     return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
68             ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
69 #endif
70 }
71 
72 // func true -> stop search and forEachManifest will return true
forEachManifest(const std::function<bool (const ManifestWithDescription &)> & func)73 static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
74     for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
75         if (mwd.manifest == nullptr) {
76             ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
77             // note, we explicitly do not retry here, so that we can detect VINTF
78             // or other bugs (b/151696835)
79             continue;
80         }
81         if (func(mwd)) return true;
82     }
83     return false;
84 }
85 
86 struct AidlName {
87     std::string package;
88     std::string iface;
89     std::string instance;
90 
fillandroid::AidlName91     static bool fill(const std::string& name, AidlName* aname) {
92         size_t firstSlash = name.find('/');
93         size_t lastDot = name.rfind('.', firstSlash);
94         if (firstSlash == std::string::npos || lastDot == std::string::npos) {
95             ALOGE("VINTF HALs require names in the format type/instance (e.g. "
96                   "some.package.foo.IFoo/default) but got: %s",
97                   name.c_str());
98             return false;
99         }
100         aname->package = name.substr(0, lastDot);
101         aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
102         aname->instance = name.substr(firstSlash + 1);
103         return true;
104     }
105 };
106 
isVintfDeclared(const std::string & name)107 static bool isVintfDeclared(const std::string& name) {
108     AidlName aname;
109     if (!AidlName::fill(name, &aname)) return false;
110 
111     bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
112         if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
113             ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
114             return true; // break
115         }
116         return false;  // continue
117     });
118 
119     if (!found) {
120         // Although it is tested, explicitly rebuilding qualified name, in case it
121         // becomes something unexpected.
122         ALOGI("Could not find %s.%s/%s in the VINTF manifest.", aname.package.c_str(),
123               aname.iface.c_str(), aname.instance.c_str());
124     }
125 
126     return found;
127 }
128 
getVintfUpdatableApex(const std::string & name)129 static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
130     AidlName aname;
131     if (!AidlName::fill(name, &aname)) return std::nullopt;
132 
133     std::optional<std::string> updatableViaApex;
134 
135     forEachManifest([&](const ManifestWithDescription& mwd) {
136         mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
137             if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
138             if (manifestInstance.package() != aname.package) return true;
139             if (manifestInstance.interface() != aname.iface) return true;
140             if (manifestInstance.instance() != aname.instance) return true;
141             updatableViaApex = manifestInstance.updatableViaApex();
142             return false; // break (libvintf uses opposite convention)
143         });
144         if (updatableViaApex.has_value()) return true; // break (found match)
145         return false; // continue
146     });
147 
148     return updatableViaApex;
149 }
150 
getVintfUpdatableInstances(const std::string & apexName)151 static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
152     std::vector<std::string> instances;
153 
154     forEachManifest([&](const ManifestWithDescription& mwd) {
155         mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
156             if (manifestInstance.format() == vintf::HalFormat::AIDL &&
157                 manifestInstance.updatableViaApex().has_value() &&
158                 manifestInstance.updatableViaApex().value() == apexName) {
159                 std::string aname = manifestInstance.package() + "." +
160                         manifestInstance.interface() + "/" + manifestInstance.instance();
161                 instances.push_back(aname);
162             }
163             return true; // continue (libvintf uses opposite convention)
164         });
165         return false; // continue
166     });
167 
168     return instances;
169 }
170 
getVintfConnectionInfo(const std::string & name)171 static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
172     AidlName aname;
173     if (!AidlName::fill(name, &aname)) return std::nullopt;
174 
175     std::optional<std::string> ip;
176     std::optional<uint64_t> port;
177     forEachManifest([&](const ManifestWithDescription& mwd) {
178         mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
179             if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
180             if (manifestInstance.package() != aname.package) return true;
181             if (manifestInstance.interface() != aname.iface) return true;
182             if (manifestInstance.instance() != aname.instance) return true;
183             ip = manifestInstance.ip();
184             port = manifestInstance.port();
185             return false; // break (libvintf uses opposite convention)
186         });
187         return false; // continue
188     });
189 
190     if (ip.has_value() && port.has_value()) {
191         ConnectionInfo info;
192         info.ipAddress = *ip;
193         info.port = *port;
194         return std::make_optional<ConnectionInfo>(info);
195     } else {
196         return std::nullopt;
197     }
198 }
199 
getVintfInstances(const std::string & interface)200 static std::vector<std::string> getVintfInstances(const std::string& interface) {
201     size_t lastDot = interface.rfind('.');
202     if (lastDot == std::string::npos) {
203         ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
204               "but got: %s",
205               interface.c_str());
206         return {};
207     }
208     const std::string package = interface.substr(0, lastDot);
209     const std::string iface = interface.substr(lastDot+1);
210 
211     std::vector<std::string> ret;
212     (void)forEachManifest([&](const ManifestWithDescription& mwd) {
213         auto instances = mwd.manifest->getAidlInstances(package, iface);
214         ret.insert(ret.end(), instances.begin(), instances.end());
215         return false;  // continue
216     });
217 
218     return ret;
219 }
220 
meetsDeclarationRequirements(const sp<IBinder> & binder,const std::string & name)221 static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
222     if (!Stability::requiresVintfDeclaration(binder)) {
223         return true;
224     }
225 
226     return isVintfDeclared(name);
227 }
228 #endif  // !VENDORSERVICEMANAGER
229 
~Service()230 ServiceManager::Service::~Service() {
231     if (hasClients) {
232         // only expected to happen on process death, we don't store the service
233         // name this late (it's in the map that holds this service), but if it
234         // is happening, we might want to change 'unlinkToDeath' to explicitly
235         // clear this bit so that we can abort in other cases, where it would
236         // mean inconsistent logic in servicemanager (unexpected and tested, but
237         // the original lazy service impl here had that bug).
238         LOG(WARNING) << "a service was removed when there are clients";
239     }
240 }
241 
ServiceManager(std::unique_ptr<Access> && access)242 ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
243 // TODO(b/151696835): reenable performance hack when we solve bug, since with
244 //     this hack and other fixes, it is unlikely we will see even an ephemeral
245 //     failure when the manifest parse fails. The goal is that the manifest will
246 //     be read incorrectly and cause the process trying to register a HAL to
247 //     fail. If this is in fact an early boot kernel contention issue, then we
248 //     will get no failure, and by its absence, be signalled to invest more
249 //     effort in re-adding this performance hack.
250 // #ifndef VENDORSERVICEMANAGER
251 //     // can process these at any times, don't want to delay first VINTF client
252 //     std::thread([] {
253 //         vintf::VintfObject::GetDeviceHalManifest();
254 //         vintf::VintfObject::GetFrameworkHalManifest();
255 //     }).detach();
256 // #endif  // !VENDORSERVICEMANAGER
257 }
~ServiceManager()258 ServiceManager::~ServiceManager() {
259     // this should only happen in tests
260 
261     for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
262         CHECK(!callbacks.empty()) << name;
263         for (const auto& callback : callbacks) {
264             CHECK(callback != nullptr) << name;
265         }
266     }
267 
268     for (const auto& [name, service] : mNameToService) {
269         CHECK(service.binder != nullptr) << name;
270     }
271 }
272 
getService(const std::string & name,sp<IBinder> * outBinder)273 Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
274     *outBinder = tryGetService(name, true);
275     // returns ok regardless of result for legacy reasons
276     return Status::ok();
277 }
278 
checkService(const std::string & name,sp<IBinder> * outBinder)279 Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
280     *outBinder = tryGetService(name, false);
281     // returns ok regardless of result for legacy reasons
282     return Status::ok();
283 }
284 
tryGetService(const std::string & name,bool startIfNotFound)285 sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
286     auto ctx = mAccess->getCallingContext();
287 
288     sp<IBinder> out;
289     Service* service = nullptr;
290     if (auto it = mNameToService.find(name); it != mNameToService.end()) {
291         service = &(it->second);
292 
293         if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
294             return nullptr;
295         }
296         out = service->binder;
297     }
298 
299     if (!mAccess->canFind(ctx, name)) {
300         return nullptr;
301     }
302 
303     if (!out && startIfNotFound) {
304         tryStartService(name);
305     }
306 
307     if (out) {
308         // Force onClients to get sent, and then make sure the timerfd won't clear it
309         // by setting guaranteeClient again. This logic could be simplified by using
310         // a time-based guarantee. However, forcing onClients(true) to get sent
311         // right here is always going to be important for processes serving multiple
312         // lazy interfaces.
313         service->guaranteeClient = true;
314         CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
315         service->guaranteeClient = true;
316     }
317 
318     return out;
319 }
320 
isValidServiceName(const std::string & name)321 bool isValidServiceName(const std::string& name) {
322     if (name.size() == 0) return false;
323     if (name.size() > 127) return false;
324 
325     for (char c : name) {
326         if (c == '_' || c == '-' || c == '.' || c == '/') continue;
327         if (c >= 'a' && c <= 'z') continue;
328         if (c >= 'A' && c <= 'Z') continue;
329         if (c >= '0' && c <= '9') continue;
330         return false;
331     }
332 
333     return true;
334 }
335 
addService(const std::string & name,const sp<IBinder> & binder,bool allowIsolated,int32_t dumpPriority)336 Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
337     auto ctx = mAccess->getCallingContext();
338 
339     if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
340         return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
341     }
342 
343     if (!mAccess->canAdd(ctx, name)) {
344         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
345     }
346 
347     if (binder == nullptr) {
348         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
349     }
350 
351     if (!isValidServiceName(name)) {
352         ALOGE("Invalid service name: %s", name.c_str());
353         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
354     }
355 
356 #ifndef VENDORSERVICEMANAGER
357     if (!meetsDeclarationRequirements(binder, name)) {
358         // already logged
359         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
360     }
361 #endif  // !VENDORSERVICEMANAGER
362 
363     if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
364         ALOGW("Dump flag priority is not set when adding %s", name.c_str());
365     }
366 
367     // implicitly unlinked when the binder is removed
368     if (binder->remoteBinder() != nullptr &&
369         binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
370         ALOGE("Could not linkToDeath when adding %s", name.c_str());
371         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
372     }
373 
374     auto it = mNameToService.find(name);
375     if (it != mNameToService.end()) {
376         const Service& existing = it->second;
377 
378         // We could do better than this because if the other service dies, it
379         // may not have an entry here. However, this case is unlikely. We are
380         // only trying to detect when two different services are accidentally installed.
381 
382         if (existing.ctx.uid != ctx.uid) {
383             ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
384                   "from UID %u. Multiple instances installed?",
385                   name.c_str(), existing.ctx.uid, ctx.uid);
386         }
387 
388         if (existing.ctx.sid != ctx.sid) {
389             ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
390                   "from SID %s. Multiple instances installed?",
391                   name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
392         }
393 
394         ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
395               "from PID %d. Bad state? Late death notification? Multiple instances installed?",
396               name.c_str(), existing.ctx.debugPid, ctx.debugPid);
397     }
398 
399     // Overwrite the old service if it exists
400     mNameToService[name] = Service{
401             .binder = binder,
402             .allowIsolated = allowIsolated,
403             .dumpPriority = dumpPriority,
404             .ctx = ctx,
405     };
406 
407     if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
408         // See also getService - handles case where client never gets the service,
409         // we want the service to quit.
410         mNameToService[name].guaranteeClient = true;
411         CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
412         mNameToService[name].guaranteeClient = true;
413 
414         for (const sp<IServiceCallback>& cb : it->second) {
415             // permission checked in registerForNotifications
416             cb->onRegistration(name, binder);
417         }
418     }
419 
420     return Status::ok();
421 }
422 
listServices(int32_t dumpPriority,std::vector<std::string> * outList)423 Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
424     if (!mAccess->canList(mAccess->getCallingContext())) {
425         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
426     }
427 
428     size_t toReserve = 0;
429     for (auto const& [name, service] : mNameToService) {
430         (void) name;
431 
432         if (service.dumpPriority & dumpPriority) ++toReserve;
433     }
434 
435     CHECK(outList->empty());
436 
437     outList->reserve(toReserve);
438     for (auto const& [name, service] : mNameToService) {
439         (void) service;
440 
441         if (service.dumpPriority & dumpPriority) {
442             outList->push_back(name);
443         }
444     }
445 
446     return Status::ok();
447 }
448 
registerForNotifications(const std::string & name,const sp<IServiceCallback> & callback)449 Status ServiceManager::registerForNotifications(
450         const std::string& name, const sp<IServiceCallback>& callback) {
451     auto ctx = mAccess->getCallingContext();
452 
453     if (!mAccess->canFind(ctx, name)) {
454         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
455     }
456 
457     // note - we could allow isolated apps to get notifications if we
458     // keep track of isolated callbacks and non-isolated callbacks, but
459     // this is done since isolated apps shouldn't access lazy services
460     // so we should be able to use different APIs to keep things simple.
461     // Here, we disallow everything, because the service might not be
462     // registered yet.
463     if (is_multiuser_uid_isolated(ctx.uid)) {
464         return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
465     }
466 
467     if (!isValidServiceName(name)) {
468         ALOGE("Invalid service name: %s", name.c_str());
469         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
470     }
471 
472     if (callback == nullptr) {
473         return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
474     }
475 
476     if (OK !=
477         IInterface::asBinder(callback)->linkToDeath(
478                 sp<ServiceManager>::fromExisting(this))) {
479         ALOGE("Could not linkToDeath when adding %s", name.c_str());
480         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
481     }
482 
483     mNameToRegistrationCallback[name].push_back(callback);
484 
485     if (auto it = mNameToService.find(name); it != mNameToService.end()) {
486         const sp<IBinder>& binder = it->second.binder;
487 
488         // never null if an entry exists
489         CHECK(binder != nullptr) << name;
490         callback->onRegistration(name, binder);
491     }
492 
493     return Status::ok();
494 }
unregisterForNotifications(const std::string & name,const sp<IServiceCallback> & callback)495 Status ServiceManager::unregisterForNotifications(
496         const std::string& name, const sp<IServiceCallback>& callback) {
497     auto ctx = mAccess->getCallingContext();
498 
499     if (!mAccess->canFind(ctx, name)) {
500         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
501     }
502 
503     bool found = false;
504 
505     auto it = mNameToRegistrationCallback.find(name);
506     if (it != mNameToRegistrationCallback.end()) {
507         removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
508     }
509 
510     if (!found) {
511         ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
512         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
513     }
514 
515     return Status::ok();
516 }
517 
isDeclared(const std::string & name,bool * outReturn)518 Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
519     auto ctx = mAccess->getCallingContext();
520 
521     if (!mAccess->canFind(ctx, name)) {
522         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
523     }
524 
525     *outReturn = false;
526 
527 #ifndef VENDORSERVICEMANAGER
528     *outReturn = isVintfDeclared(name);
529 #endif
530     return Status::ok();
531 }
532 
getDeclaredInstances(const std::string & interface,std::vector<std::string> * outReturn)533 binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
534     auto ctx = mAccess->getCallingContext();
535 
536     std::vector<std::string> allInstances;
537 #ifndef VENDORSERVICEMANAGER
538     allInstances = getVintfInstances(interface);
539 #endif
540 
541     outReturn->clear();
542 
543     for (const std::string& instance : allInstances) {
544         if (mAccess->canFind(ctx, interface + "/" + instance)) {
545             outReturn->push_back(instance);
546         }
547     }
548 
549     if (outReturn->size() == 0 && allInstances.size() != 0) {
550         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
551     }
552 
553     return Status::ok();
554 }
555 
updatableViaApex(const std::string & name,std::optional<std::string> * outReturn)556 Status ServiceManager::updatableViaApex(const std::string& name,
557                                         std::optional<std::string>* outReturn) {
558     auto ctx = mAccess->getCallingContext();
559 
560     if (!mAccess->canFind(ctx, name)) {
561         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
562     }
563 
564     *outReturn = std::nullopt;
565 
566 #ifndef VENDORSERVICEMANAGER
567     *outReturn = getVintfUpdatableApex(name);
568 #endif
569     return Status::ok();
570 }
571 
getUpdatableNames(const std::string & apexName,std::vector<std::string> * outReturn)572 Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
573                                          std::vector<std::string>* outReturn) {
574     auto ctx = mAccess->getCallingContext();
575 
576     std::vector<std::string> apexUpdatableInstances;
577 #ifndef VENDORSERVICEMANAGER
578     apexUpdatableInstances = getVintfUpdatableInstances(apexName);
579 #endif
580 
581     outReturn->clear();
582 
583     for (const std::string& instance : apexUpdatableInstances) {
584         if (mAccess->canFind(ctx, instance)) {
585             outReturn->push_back(instance);
586         }
587     }
588 
589     if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
590         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
591     }
592 
593     return Status::ok();
594 }
595 
getConnectionInfo(const std::string & name,std::optional<ConnectionInfo> * outReturn)596 Status ServiceManager::getConnectionInfo(const std::string& name,
597                                          std::optional<ConnectionInfo>* outReturn) {
598     auto ctx = mAccess->getCallingContext();
599 
600     if (!mAccess->canFind(ctx, name)) {
601         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
602     }
603 
604     *outReturn = std::nullopt;
605 
606 #ifndef VENDORSERVICEMANAGER
607     *outReturn = getVintfConnectionInfo(name);
608 #endif
609     return Status::ok();
610 }
611 
removeRegistrationCallback(const wp<IBinder> & who,ServiceCallbackMap::iterator * it,bool * found)612 void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
613                                     ServiceCallbackMap::iterator* it,
614                                     bool* found) {
615     std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
616 
617     for (auto lit = listeners.begin(); lit != listeners.end();) {
618         if (IInterface::asBinder(*lit) == who) {
619             if(found) *found = true;
620             lit = listeners.erase(lit);
621         } else {
622             ++lit;
623         }
624     }
625 
626     if (listeners.empty()) {
627         *it = mNameToRegistrationCallback.erase(*it);
628     } else {
629         (*it)++;
630     }
631 }
632 
binderDied(const wp<IBinder> & who)633 void ServiceManager::binderDied(const wp<IBinder>& who) {
634     for (auto it = mNameToService.begin(); it != mNameToService.end();) {
635         if (who == it->second.binder) {
636             it = mNameToService.erase(it);
637         } else {
638             ++it;
639         }
640     }
641 
642     for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
643         removeRegistrationCallback(who, &it, nullptr /*found*/);
644     }
645 
646     for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
647         removeClientCallback(who, &it);
648     }
649 }
650 
tryStartService(const std::string & name)651 void ServiceManager::tryStartService(const std::string& name) {
652     ALOGI("Since '%s' could not be found, trying to start it as a lazy AIDL service. (if it's not "
653           "configured to be a lazy service, it may be stuck starting or still starting).",
654           name.c_str());
655 
656     std::thread([=] {
657         if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
658             ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
659                   "this happens when a "
660                   "service is not installed, but if the service is intended to be used as a "
661                   "lazy service, then it may be configured incorrectly.",
662                   name.c_str());
663         }
664     }).detach();
665 }
666 
registerClientCallback(const std::string & name,const sp<IBinder> & service,const sp<IClientCallback> & cb)667 Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
668                                               const sp<IClientCallback>& cb) {
669     if (cb == nullptr) {
670         return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
671     }
672 
673     auto ctx = mAccess->getCallingContext();
674     if (!mAccess->canAdd(ctx, name)) {
675         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
676     }
677 
678     auto serviceIt = mNameToService.find(name);
679     if (serviceIt == mNameToService.end()) {
680         ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
681         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
682     }
683 
684     if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
685         ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
686         return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
687                                          "Only service can register client callback for itself.");
688     }
689 
690     if (serviceIt->second.binder != service) {
691         ALOGW("Tried to register client callback for %s but a different service is registered "
692               "under this name.",
693               name.c_str());
694         return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
695     }
696 
697     if (OK !=
698         IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
699         ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
700         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
701     }
702 
703     // make sure all callbacks have been told about a consistent state - b/278038751
704     if (serviceIt->second.hasClients) {
705         cb->onClients(service, true);
706     }
707 
708     mNameToClientCallback[name].push_back(cb);
709 
710     return Status::ok();
711 }
712 
removeClientCallback(const wp<IBinder> & who,ClientCallbackMap::iterator * it)713 void ServiceManager::removeClientCallback(const wp<IBinder>& who,
714                                           ClientCallbackMap::iterator* it) {
715     std::vector<sp<IClientCallback>>& listeners = (*it)->second;
716 
717     for (auto lit = listeners.begin(); lit != listeners.end();) {
718         if (IInterface::asBinder(*lit) == who) {
719             lit = listeners.erase(lit);
720         } else {
721             ++lit;
722         }
723     }
724 
725     if (listeners.empty()) {
726         *it = mNameToClientCallback.erase(*it);
727     } else {
728         (*it)++;
729     }
730 }
731 
getNodeStrongRefCount()732 ssize_t ServiceManager::Service::getNodeStrongRefCount() {
733     sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
734     if (bpBinder == nullptr) return -1;
735 
736     return ProcessState::self()->getStrongRefCountForNode(bpBinder);
737 }
738 
handleClientCallbacks()739 void ServiceManager::handleClientCallbacks() {
740     for (const auto& [name, service] : mNameToService) {
741         handleServiceClientCallback(1 /* sm has one refcount */, name, true);
742     }
743 }
744 
handleServiceClientCallback(size_t knownClients,const std::string & serviceName,bool isCalledOnInterval)745 bool ServiceManager::handleServiceClientCallback(size_t knownClients,
746                                                  const std::string& serviceName,
747                                                  bool isCalledOnInterval) {
748     auto serviceIt = mNameToService.find(serviceName);
749     if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
750         return true; // return we do have clients a.k.a. DON'T DO ANYTHING
751     }
752 
753     Service& service = serviceIt->second;
754     ssize_t count = service.getNodeStrongRefCount();
755 
756     // binder driver doesn't support this feature, consider we have clients
757     if (count == -1) return true;
758 
759     bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
760 
761     if (service.guaranteeClient) {
762         if (!service.hasClients && !hasKernelReportedClients) {
763             sendClientCallbackNotifications(serviceName, true,
764                                             "service is guaranteed to be in use");
765         }
766 
767         // guarantee is temporary
768         service.guaranteeClient = false;
769     }
770 
771     // Regardless of this situation, we want to give this notification as soon as possible.
772     // This way, we have a chance of preventing further thrashing.
773     if (hasKernelReportedClients && !service.hasClients) {
774         sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
775     }
776 
777     // But limit rate of shutting down service.
778     if (isCalledOnInterval) {
779         if (!hasKernelReportedClients && service.hasClients) {
780             sendClientCallbackNotifications(serviceName, false,
781                                             "we now have no record of a client");
782         }
783     }
784 
785     // May be different than 'hasKernelReportedClients'. We intentionally delay
786     // information about clients going away to reduce thrashing.
787     return service.hasClients;
788 }
789 
sendClientCallbackNotifications(const std::string & serviceName,bool hasClients,const char * context)790 void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
791                                                      bool hasClients, const char* context) {
792     auto serviceIt = mNameToService.find(serviceName);
793     if (serviceIt == mNameToService.end()) {
794         ALOGW("sendClientCallbackNotifications could not find service %s when %s",
795               serviceName.c_str(), context);
796         return;
797     }
798     Service& service = serviceIt->second;
799 
800     CHECK_NE(hasClients, service.hasClients) << context;
801 
802     ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
803           hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
804 
805     auto ccIt = mNameToClientCallback.find(serviceName);
806     CHECK(ccIt != mNameToClientCallback.end())
807             << "sendClientCallbackNotifications could not find callbacks for service when "
808             << context;
809 
810     for (const auto& callback : ccIt->second) {
811         callback->onClients(service.binder, hasClients);
812     }
813 
814     service.hasClients = hasClients;
815 }
816 
tryUnregisterService(const std::string & name,const sp<IBinder> & binder)817 Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
818     if (binder == nullptr) {
819         return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
820     }
821 
822     auto ctx = mAccess->getCallingContext();
823     if (!mAccess->canAdd(ctx, name)) {
824         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
825     }
826 
827     auto serviceIt = mNameToService.find(name);
828     if (serviceIt == mNameToService.end()) {
829         ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
830               name.c_str());
831         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
832     }
833 
834     if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
835         ALOGW("Only a server can unregister itself (for %s)", name.c_str());
836         return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
837                                          "Service can only unregister itself.");
838     }
839 
840     sp<IBinder> storedBinder = serviceIt->second.binder;
841 
842     if (binder != storedBinder) {
843         ALOGW("Tried to unregister %s, but a different service is registered under this name.",
844               name.c_str());
845         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
846                                          "Different service registered under this name.");
847     }
848 
849     // important because we don't have timer-based guarantees, we don't want to clear
850     // this
851     if (serviceIt->second.guaranteeClient) {
852         ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
853         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
854                                          "Can't unregister, pending client.");
855     }
856 
857     // - kernel driver will hold onto one refcount (during this transaction)
858     // - servicemanager has a refcount (guaranteed by this transaction)
859     constexpr size_t kKnownClients = 2;
860 
861     if (handleServiceClientCallback(kKnownClients, name, false)) {
862         ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
863 
864         // Since we had a failed registration attempt, and the HIDL implementation of
865         // delaying service shutdown for multiple periods wasn't ported here... this may
866         // help reduce thrashing, but we should be able to remove it.
867         serviceIt->second.guaranteeClient = true;
868 
869         return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
870                                          "Can't unregister, known client.");
871     }
872 
873     ALOGI("Unregistering %s", name.c_str());
874     mNameToService.erase(name);
875 
876     return Status::ok();
877 }
878 
getServiceDebugInfo(std::vector<ServiceDebugInfo> * outReturn)879 Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
880     if (!mAccess->canList(mAccess->getCallingContext())) {
881         return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
882     }
883 
884     outReturn->reserve(mNameToService.size());
885     for (auto const& [name, service] : mNameToService) {
886         ServiceDebugInfo info;
887         info.name = name;
888         info.debugPid = service.ctx.debugPid;
889 
890         outReturn->push_back(std::move(info));
891     }
892 
893     return Status::ok();
894 }
895 
clear()896 void ServiceManager::clear() {
897     mNameToService.clear();
898     mNameToRegistrationCallback.clear();
899     mNameToClientCallback.clear();
900 }
901 
902 }  // namespace android
903