blob: 4374abe2ef690c3e1c7ce1e80d5830586a86563a [file] [log] [blame]
Steven Moreland80e1e6d2019-06-21 12:35:59 -07001/*
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>
Jon Spivack0d844302019-07-22 18:40:34 -070020#include <android-base/properties.h>
Jon Spivack9f503a42019-10-22 16:49:19 -070021#include <binder/BpBinder.h>
22#include <binder/IPCThreadState.h>
23#include <binder/ProcessState.h>
Steven Moreland86a17f82019-09-10 10:18:00 -070024#include <binder/Stability.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070025#include <cutils/android_filesystem_config.h>
26#include <cutils/multiuser.h>
Jon Spivack0d844302019-07-22 18:40:34 -070027#include <thread>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070028
Steven Moreland86a17f82019-09-10 10:18:00 -070029#ifndef VENDORSERVICEMANAGER
30#include <vintf/VintfObject.h>
Yifan Hong0a9b56e2021-11-30 16:45:40 -080031#ifdef __ANDROID_RECOVERY__
32#include <vintf/VintfObjectRecovery.h>
33#endif // __ANDROID_RECOVERY__
Steven Moreland86a17f82019-09-10 10:18:00 -070034#include <vintf/constants.h>
35#endif // !VENDORSERVICEMANAGER
36
Steven Moreland80e1e6d2019-06-21 12:35:59 -070037using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070038using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070039
40namespace android {
41
Steven Moreland86a17f82019-09-10 10:18:00 -070042#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080043
Steven Moreland2e293aa2020-09-23 00:25:16 +000044struct ManifestWithDescription {
45 std::shared_ptr<const vintf::HalManifest> manifest;
46 const char* description;
47};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080048static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
49#ifdef __ANDROID_RECOVERY__
50 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
51 if (vintfObject == nullptr) {
52 LOG(ERROR) << "NULL VintfObjectRecovery!";
53 return {};
54 }
55 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
56#else
57 auto vintfObject = vintf::VintfObject::GetInstance();
58 if (vintfObject == nullptr) {
59 LOG(ERROR) << "NULL VintfObject!";
60 return {};
61 }
62 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
63 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
64#endif
65}
66
Steven Moreland2e293aa2020-09-23 00:25:16 +000067// func true -> stop search and forEachManifest will return true
68static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080069 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000070 if (mwd.manifest == nullptr) {
71 LOG(ERROR) << "NULL VINTF MANIFEST!: " << mwd.description;
72 // note, we explicitly do not retry here, so that we can detect VINTF
73 // or other bugs (b/151696835)
74 continue;
75 }
76 if (func(mwd)) return true;
77 }
78 return false;
79}
80
Steven Morelandedd4e072021-04-21 00:27:29 +000081struct AidlName {
82 std::string package;
83 std::string iface;
84 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070085
Steven Morelandedd4e072021-04-21 00:27:29 +000086 static bool fill(const std::string& name, AidlName* aname) {
87 size_t firstSlash = name.find('/');
88 size_t lastDot = name.rfind('.', firstSlash);
89 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
90 LOG(ERROR) << "VINTF HALs require names in the format type/instance (e.g. "
91 << "some.package.foo.IFoo/default) but got: " << name;
92 return false;
93 }
94 aname->package = name.substr(0, lastDot);
95 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
96 aname->instance = name.substr(firstSlash + 1);
97 return true;
98 }
99};
100
101static bool isVintfDeclared(const std::string& name) {
102 AidlName aname;
103 if (!AidlName::fill(name, &aname)) return false;
104
105 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
106 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Steven Moreland2edde8e2020-04-30 17:04:54 -0700107 LOG(INFO) << "Found " << name << " in " << mwd.description << " VINTF manifest.";
Steven Morelandedd4e072021-04-21 00:27:29 +0000108 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700109 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000110 return false; // continue
111 });
112
113 if (!found) {
114 // Although it is tested, explicitly rebuilding qualified name, in case it
115 // becomes something unexpected.
Steven Morelandedd4e072021-04-21 00:27:29 +0000116 LOG(ERROR) << "Could not find " << aname.package << "." << aname.iface << "/"
117 << aname.instance << " in the VINTF manifest.";
Steven Moreland86a17f82019-09-10 10:18:00 -0700118 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700119
Steven Moreland2e293aa2020-09-23 00:25:16 +0000120 return found;
121}
122
Steven Morelandedd4e072021-04-21 00:27:29 +0000123static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
124 AidlName aname;
125 if (!AidlName::fill(name, &aname)) return std::nullopt;
126
127 std::optional<std::string> updatableViaApex;
128
129 forEachManifest([&](const ManifestWithDescription& mwd) {
130 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
131 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
132 if (manifestInstance.package() != aname.package) return true;
133 if (manifestInstance.interface() != aname.iface) return true;
134 if (manifestInstance.instance() != aname.instance) return true;
135 updatableViaApex = manifestInstance.updatableViaApex();
136 return false; // break (libvintf uses opposite convention)
137 });
138 return false; // continue
139 });
140
141 return updatableViaApex;
142}
143
Devin Moore5e4c2f12021-09-09 22:36:33 +0000144static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
145 AidlName aname;
146 if (!AidlName::fill(name, &aname)) return std::nullopt;
147
148 std::optional<std::string> ip;
149 std::optional<uint64_t> port;
150 forEachManifest([&](const ManifestWithDescription& mwd) {
151 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
152 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
153 if (manifestInstance.package() != aname.package) return true;
154 if (manifestInstance.interface() != aname.iface) return true;
155 if (manifestInstance.instance() != aname.instance) return true;
156 ip = manifestInstance.ip();
157 port = manifestInstance.port();
158 return false; // break (libvintf uses opposite convention)
159 });
160 return false; // continue
161 });
162
163 if (ip.has_value() && port.has_value()) {
164 ConnectionInfo info;
165 info.ipAddress = *ip;
166 info.port = *port;
167 return std::make_optional<ConnectionInfo>(info);
168 } else {
169 return std::nullopt;
170 }
171}
172
Steven Moreland2e293aa2020-09-23 00:25:16 +0000173static std::vector<std::string> getVintfInstances(const std::string& interface) {
174 size_t lastDot = interface.rfind('.');
175 if (lastDot == std::string::npos) {
176 LOG(ERROR) << "VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) but got: " << interface;
177 return {};
178 }
179 const std::string package = interface.substr(0, lastDot);
180 const std::string iface = interface.substr(lastDot+1);
181
182 std::vector<std::string> ret;
183 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
184 auto instances = mwd.manifest->getAidlInstances(package, iface);
185 ret.insert(ret.end(), instances.begin(), instances.end());
186 return false; // continue
187 });
188
189 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700190}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700191
192static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
193 if (!Stability::requiresVintfDeclaration(binder)) {
194 return true;
195 }
196
197 return isVintfDeclared(name);
198}
Steven Moreland86a17f82019-09-10 10:18:00 -0700199#endif // !VENDORSERVICEMANAGER
200
Steven Morelandd13f08b2019-11-18 14:23:09 -0800201ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700202// TODO(b/151696835): reenable performance hack when we solve bug, since with
203// this hack and other fixes, it is unlikely we will see even an ephemeral
204// failure when the manifest parse fails. The goal is that the manifest will
205// be read incorrectly and cause the process trying to register a HAL to
206// fail. If this is in fact an early boot kernel contention issue, then we
207// will get no failure, and by its absence, be signalled to invest more
208// effort in re-adding this performance hack.
209// #ifndef VENDORSERVICEMANAGER
210// // can process these at any times, don't want to delay first VINTF client
211// std::thread([] {
212// vintf::VintfObject::GetDeviceHalManifest();
213// vintf::VintfObject::GetFrameworkHalManifest();
214// }).detach();
215// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800216}
Steven Moreland130242d2019-08-26 17:41:32 -0700217ServiceManager::~ServiceManager() {
218 // this should only happen in tests
219
Jon Spivackf288b1d2019-12-19 17:15:51 -0800220 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700221 CHECK(!callbacks.empty()) << name;
222 for (const auto& callback : callbacks) {
223 CHECK(callback != nullptr) << name;
224 }
225 }
226
Steven Moreland130242d2019-08-26 17:41:32 -0700227 for (const auto& [name, service] : mNameToService) {
228 CHECK(service.binder != nullptr) << name;
229 }
230}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700231
232Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700233 *outBinder = tryGetService(name, true);
234 // returns ok regardless of result for legacy reasons
235 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700236}
237
238Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700239 *outBinder = tryGetService(name, false);
240 // returns ok regardless of result for legacy reasons
241 return Status::ok();
242}
243
244sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700245 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700246
Jon Spivack0d844302019-07-22 18:40:34 -0700247 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700248 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700249 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700250 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700251
Jon Spivack9f503a42019-10-22 16:49:19 -0700252 if (!service->allowIsolated) {
Jon Spivack0d844302019-07-22 18:40:34 -0700253 uid_t appid = multiuser_get_app_id(ctx.uid);
254 bool isIsolated = appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700255
Jon Spivack0d844302019-07-22 18:40:34 -0700256 if (isIsolated) {
257 return nullptr;
258 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700259 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700260 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700261 }
262
Steven Morelanda9fe4742019-07-18 14:45:20 -0700263 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700264 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700265 }
266
Jon Spivack0d844302019-07-22 18:40:34 -0700267 if (!out && startIfNotFound) {
268 tryStartService(name);
269 }
270
Jon Spivack9f503a42019-10-22 16:49:19 -0700271 if (out) {
272 // Setting this guarantee each time we hand out a binder ensures that the client-checking
273 // loop knows about the event even if the client immediately drops the service
274 service->guaranteeClient = true;
275 }
276
Jon Spivack0d844302019-07-22 18:40:34 -0700277 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700278}
279
Steven Moreland905e2e82019-07-17 11:05:45 -0700280bool isValidServiceName(const std::string& name) {
281 if (name.size() == 0) return false;
282 if (name.size() > 127) return false;
283
284 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700285 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700286 if (c >= 'a' && c <= 'z') continue;
287 if (c >= 'A' && c <= 'Z') continue;
288 if (c >= '0' && c <= '9') continue;
289 return false;
290 }
291
292 return true;
293}
294
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700295Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700296 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700297
298 // apps cannot add services
299 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
300 return Status::fromExceptionCode(Status::EX_SECURITY);
301 }
302
Steven Morelanda9fe4742019-07-18 14:45:20 -0700303 if (!mAccess->canAdd(ctx, name)) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700304 return Status::fromExceptionCode(Status::EX_SECURITY);
305 }
306
307 if (binder == nullptr) {
308 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
309 }
310
Steven Moreland905e2e82019-07-17 11:05:45 -0700311 if (!isValidServiceName(name)) {
312 LOG(ERROR) << "Invalid service name: " << name;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700313 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
314 }
315
Steven Moreland86a17f82019-09-10 10:18:00 -0700316#ifndef VENDORSERVICEMANAGER
317 if (!meetsDeclarationRequirements(binder, name)) {
318 // already logged
319 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
320 }
321#endif // !VENDORSERVICEMANAGER
322
Steven Moreland88860b02019-08-12 14:24:14 -0700323 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000324 if (binder->remoteBinder() != nullptr &&
325 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700326 LOG(ERROR) << "Could not linkToDeath when adding " << name;
327 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
328 }
329
Devin Moore05ffe522020-08-06 13:58:29 -0700330 // Overwrite the old service if it exists
331 mNameToService[name] = Service {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700332 .binder = binder,
333 .allowIsolated = allowIsolated,
334 .dumpPriority = dumpPriority,
Jon Spivack9f503a42019-10-22 16:49:19 -0700335 .debugPid = ctx.debugPid,
Devin Moore05ffe522020-08-06 13:58:29 -0700336 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700337
Jon Spivackf288b1d2019-12-19 17:15:51 -0800338 auto it = mNameToRegistrationCallback.find(name);
339 if (it != mNameToRegistrationCallback.end()) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700340 for (const sp<IServiceCallback>& cb : it->second) {
Devin Moore05ffe522020-08-06 13:58:29 -0700341 mNameToService[name].guaranteeClient = true;
Steven Moreland27cfab02019-08-12 14:34:16 -0700342 // permission checked in registerForNotifications
343 cb->onRegistration(name, binder);
344 }
345 }
346
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700347 return Status::ok();
348}
349
350Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700351 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700352 return Status::fromExceptionCode(Status::EX_SECURITY);
353 }
354
355 size_t toReserve = 0;
356 for (auto const& [name, service] : mNameToService) {
357 (void) name;
358
359 if (service.dumpPriority & dumpPriority) ++toReserve;
360 }
361
362 CHECK(outList->empty());
363
364 outList->reserve(toReserve);
365 for (auto const& [name, service] : mNameToService) {
366 (void) service;
367
368 if (service.dumpPriority & dumpPriority) {
369 outList->push_back(name);
370 }
371 }
372
373 return Status::ok();
374}
375
Steven Moreland27cfab02019-08-12 14:34:16 -0700376Status ServiceManager::registerForNotifications(
377 const std::string& name, const sp<IServiceCallback>& callback) {
378 auto ctx = mAccess->getCallingContext();
379
380 if (!mAccess->canFind(ctx, name)) {
381 return Status::fromExceptionCode(Status::EX_SECURITY);
382 }
383
384 if (!isValidServiceName(name)) {
385 LOG(ERROR) << "Invalid service name: " << name;
386 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
387 }
388
389 if (callback == nullptr) {
390 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
391 }
392
Steven Morelandb0983182021-04-02 03:14:04 +0000393 if (OK !=
394 IInterface::asBinder(callback)->linkToDeath(
395 sp<ServiceManager>::fromExisting(this))) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700396 LOG(ERROR) << "Could not linkToDeath when adding " << name;
397 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
398 }
399
Jon Spivackf288b1d2019-12-19 17:15:51 -0800400 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700401
402 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
403 const sp<IBinder>& binder = it->second.binder;
404
405 // never null if an entry exists
406 CHECK(binder != nullptr) << name;
407 callback->onRegistration(name, binder);
408 }
409
410 return Status::ok();
411}
412Status ServiceManager::unregisterForNotifications(
413 const std::string& name, const sp<IServiceCallback>& callback) {
414 auto ctx = mAccess->getCallingContext();
415
416 if (!mAccess->canFind(ctx, name)) {
417 return Status::fromExceptionCode(Status::EX_SECURITY);
418 }
419
420 bool found = false;
421
Jon Spivackf288b1d2019-12-19 17:15:51 -0800422 auto it = mNameToRegistrationCallback.find(name);
423 if (it != mNameToRegistrationCallback.end()) {
424 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700425 }
426
427 if (!found) {
428 LOG(ERROR) << "Trying to unregister callback, but none exists " << name;
429 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
430 }
431
432 return Status::ok();
433}
434
Steven Morelandb82b8f82019-10-28 10:52:34 -0700435Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
436 auto ctx = mAccess->getCallingContext();
437
438 if (!mAccess->canFind(ctx, name)) {
439 return Status::fromExceptionCode(Status::EX_SECURITY);
440 }
441
442 *outReturn = false;
443
444#ifndef VENDORSERVICEMANAGER
445 *outReturn = isVintfDeclared(name);
446#endif
447 return Status::ok();
448}
449
Steven Moreland2e293aa2020-09-23 00:25:16 +0000450binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
451 auto ctx = mAccess->getCallingContext();
452
453 std::vector<std::string> allInstances;
454#ifndef VENDORSERVICEMANAGER
455 allInstances = getVintfInstances(interface);
456#endif
457
458 outReturn->clear();
459
460 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000461 if (mAccess->canFind(ctx, interface + "/" + instance)) {
462 outReturn->push_back(instance);
463 }
464 }
465
466 if (outReturn->size() == 0 && allInstances.size() != 0) {
467 return Status::fromExceptionCode(Status::EX_SECURITY);
468 }
469
470 return Status::ok();
471}
472
Steven Morelandedd4e072021-04-21 00:27:29 +0000473Status ServiceManager::updatableViaApex(const std::string& name,
474 std::optional<std::string>* outReturn) {
475 auto ctx = mAccess->getCallingContext();
476
477 if (!mAccess->canFind(ctx, name)) {
478 return Status::fromExceptionCode(Status::EX_SECURITY);
479 }
480
481 *outReturn = std::nullopt;
482
483#ifndef VENDORSERVICEMANAGER
484 *outReturn = getVintfUpdatableApex(name);
485#endif
486 return Status::ok();
487}
488
Devin Moore5e4c2f12021-09-09 22:36:33 +0000489Status ServiceManager::getConnectionInfo(const std::string& name,
490 std::optional<ConnectionInfo>* outReturn) {
491 auto ctx = mAccess->getCallingContext();
492
493 if (!mAccess->canFind(ctx, name)) {
494 return Status::fromExceptionCode(Status::EX_SECURITY);
495 }
496
497 *outReturn = std::nullopt;
498
499#ifndef VENDORSERVICEMANAGER
500 *outReturn = getVintfConnectionInfo(name);
501#endif
502 return Status::ok();
503}
504
Jon Spivackf288b1d2019-12-19 17:15:51 -0800505void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
506 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700507 bool* found) {
508 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
509
510 for (auto lit = listeners.begin(); lit != listeners.end();) {
511 if (IInterface::asBinder(*lit) == who) {
512 if(found) *found = true;
513 lit = listeners.erase(lit);
514 } else {
515 ++lit;
516 }
517 }
518
519 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800520 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700521 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800522 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700523 }
524}
525
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700526void ServiceManager::binderDied(const wp<IBinder>& who) {
527 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
528 if (who == it->second.binder) {
529 it = mNameToService.erase(it);
530 } else {
531 ++it;
532 }
533 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700534
Jon Spivackf288b1d2019-12-19 17:15:51 -0800535 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
536 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700537 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700538
539 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
540 removeClientCallback(who, &it);
541 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700542}
543
Jon Spivack0d844302019-07-22 18:40:34 -0700544void ServiceManager::tryStartService(const std::string& name) {
545 ALOGI("Since '%s' could not be found, trying to start it as a lazy AIDL service",
546 name.c_str());
547
548 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000549 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
550 LOG(INFO) << "Tried to start aidl service " << name
551 << " as a lazy service, but was unable to. Usually this happens when a "
552 "service is not installed, but if the service is intended to be used as a "
553 "lazy service, then it may be configured incorrectly.";
554 }
Jon Spivack0d844302019-07-22 18:40:34 -0700555 }).detach();
556}
557
Jon Spivack9f503a42019-10-22 16:49:19 -0700558Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
559 const sp<IClientCallback>& cb) {
560 if (cb == nullptr) {
561 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
562 }
563
564 auto ctx = mAccess->getCallingContext();
565 if (!mAccess->canAdd(ctx, name)) {
566 return Status::fromExceptionCode(Status::EX_SECURITY);
567 }
568
569 auto serviceIt = mNameToService.find(name);
570 if (serviceIt == mNameToService.end()) {
571 LOG(ERROR) << "Could not add callback for nonexistent service: " << name;
572 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
573 }
574
575 if (serviceIt->second.debugPid != IPCThreadState::self()->getCallingPid()) {
576 LOG(WARNING) << "Only a server can register for client callbacks (for " << name << ")";
577 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
578 }
579
580 if (serviceIt->second.binder != service) {
581 LOG(WARNING) << "Tried to register client callback for " << name
582 << " but a different service is registered under this name.";
583 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
584 }
585
Steven Morelandb0983182021-04-02 03:14:04 +0000586 if (OK !=
587 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700588 LOG(ERROR) << "Could not linkToDeath when adding client callback for " << name;
589 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
590 }
591
592 mNameToClientCallback[name].push_back(cb);
593
594 return Status::ok();
595}
596
597void ServiceManager::removeClientCallback(const wp<IBinder>& who,
598 ClientCallbackMap::iterator* it) {
599 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
600
601 for (auto lit = listeners.begin(); lit != listeners.end();) {
602 if (IInterface::asBinder(*lit) == who) {
603 lit = listeners.erase(lit);
604 } else {
605 ++lit;
606 }
607 }
608
609 if (listeners.empty()) {
610 *it = mNameToClientCallback.erase(*it);
611 } else {
612 (*it)++;
613 }
614}
615
616ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000617 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700618 if (bpBinder == nullptr) return -1;
619
Steven Morelande8393882020-12-18 02:27:20 +0000620 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700621}
622
623void ServiceManager::handleClientCallbacks() {
624 for (const auto& [name, service] : mNameToService) {
Jon Spivackd9533c22020-01-27 22:19:22 +0000625 handleServiceClientCallback(name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700626 }
627}
628
Jon Spivackd9533c22020-01-27 22:19:22 +0000629ssize_t ServiceManager::handleServiceClientCallback(const std::string& serviceName,
630 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700631 auto serviceIt = mNameToService.find(serviceName);
632 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
633 return -1;
634 }
635
636 Service& service = serviceIt->second;
637 ssize_t count = service.getNodeStrongRefCount();
638
639 // binder driver doesn't support this feature
640 if (count == -1) return count;
641
642 bool hasClients = count > 1; // this process holds a strong count
643
644 if (service.guaranteeClient) {
645 // we have no record of this client
646 if (!service.hasClients && !hasClients) {
647 sendClientCallbackNotifications(serviceName, true);
648 }
649
650 // guarantee is temporary
651 service.guaranteeClient = false;
652 }
653
Jon Spivackd9533c22020-01-27 22:19:22 +0000654 // only send notifications if this was called via the interval checking workflow
655 if (isCalledOnInterval) {
656 if (hasClients && !service.hasClients) {
657 // client was retrieved in some other way
658 sendClientCallbackNotifications(serviceName, true);
659 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700660
Jon Spivackd9533c22020-01-27 22:19:22 +0000661 // there are no more clients, but the callback has not been called yet
662 if (!hasClients && service.hasClients) {
663 sendClientCallbackNotifications(serviceName, false);
664 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700665 }
666
667 return count;
668}
669
670void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName, bool hasClients) {
671 auto serviceIt = mNameToService.find(serviceName);
672 if (serviceIt == mNameToService.end()) {
673 LOG(WARNING) << "sendClientCallbackNotifications could not find service " << serviceName;
674 return;
675 }
676 Service& service = serviceIt->second;
677
678 CHECK(hasClients != service.hasClients) << "Record shows: " << service.hasClients
679 << " so we can't tell clients again that we have client: " << hasClients;
680
681 LOG(INFO) << "Notifying " << serviceName << " they have clients: " << hasClients;
682
683 auto ccIt = mNameToClientCallback.find(serviceName);
684 CHECK(ccIt != mNameToClientCallback.end())
685 << "sendClientCallbackNotifications could not find callbacks for service ";
686
687 for (const auto& callback : ccIt->second) {
688 callback->onClients(service.binder, hasClients);
689 }
690
691 service.hasClients = hasClients;
692}
693
694Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
695 if (binder == nullptr) {
696 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
697 }
698
699 auto ctx = mAccess->getCallingContext();
700 if (!mAccess->canAdd(ctx, name)) {
701 return Status::fromExceptionCode(Status::EX_SECURITY);
702 }
703
704 auto serviceIt = mNameToService.find(name);
705 if (serviceIt == mNameToService.end()) {
706 LOG(WARNING) << "Tried to unregister " << name
707 << ", but that service wasn't registered to begin with.";
708 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
709 }
710
711 if (serviceIt->second.debugPid != IPCThreadState::self()->getCallingPid()) {
712 LOG(WARNING) << "Only a server can unregister itself (for " << name << ")";
713 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
714 }
715
716 sp<IBinder> storedBinder = serviceIt->second.binder;
717
718 if (binder != storedBinder) {
719 LOG(WARNING) << "Tried to unregister " << name
720 << ", but a different service is registered under this name.";
721 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
722 }
723
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700724 if (serviceIt->second.guaranteeClient) {
725 LOG(INFO) << "Tried to unregister " << name << ", but there is about to be a client.";
726 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
727 }
728
Jon Spivackd9533c22020-01-27 22:19:22 +0000729 int clients = handleServiceClientCallback(name, false);
Jon Spivack9f503a42019-10-22 16:49:19 -0700730
731 // clients < 0: feature not implemented or other error. Assume clients.
732 // Otherwise:
733 // - kernel driver will hold onto one refcount (during this transaction)
734 // - servicemanager has a refcount (guaranteed by this transaction)
735 // So, if clients > 2, then at least one other service on the system must hold a refcount.
736 if (clients < 0 || clients > 2) {
737 // client callbacks are either disabled or there are other clients
Jon Spivackd9533c22020-01-27 22:19:22 +0000738 LOG(INFO) << "Tried to unregister " << name << ", but there are clients: " << clients;
Jon Spivack620d2dc2020-03-06 13:58:01 -0800739 // Set this flag to ensure the clients are acknowledged in the next callback
740 serviceIt->second.guaranteeClient = true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700741 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
742 }
743
744 mNameToService.erase(name);
745
746 return Status::ok();
747}
748
Steven Moreland3ea43272021-01-28 22:49:28 +0000749Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
750 if (!mAccess->canList(mAccess->getCallingContext())) {
751 return Status::fromExceptionCode(Status::EX_SECURITY);
752 }
753
754 outReturn->reserve(mNameToService.size());
755 for (auto const& [name, service] : mNameToService) {
756 ServiceDebugInfo info;
757 info.name = name;
758 info.debugPid = service.debugPid;
759
760 outReturn->push_back(std::move(info));
761 }
762
763 return Status::ok();
764}
765
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700766} // namespace android