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