blob: c8355e2b6b2fbc072a5d2abbc6436419b22ecbbd [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>
31#include <vintf/constants.h>
32#endif // !VENDORSERVICEMANAGER
33
Steven Moreland80e1e6d2019-06-21 12:35:59 -070034using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070035using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070036
37namespace android {
38
Steven Moreland86a17f82019-09-10 10:18:00 -070039#ifndef VENDORSERVICEMANAGER
Steven Moreland2e293aa2020-09-23 00:25:16 +000040struct ManifestWithDescription {
41 std::shared_ptr<const vintf::HalManifest> manifest;
42 const char* description;
43};
44// func true -> stop search and forEachManifest will return true
45static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
46 for (const ManifestWithDescription& mwd : {
47 ManifestWithDescription{ vintf::VintfObject::GetDeviceHalManifest(), "device" },
48 ManifestWithDescription{ vintf::VintfObject::GetFrameworkHalManifest(), "framework" },
49 }) {
50 if (mwd.manifest == nullptr) {
51 LOG(ERROR) << "NULL VINTF MANIFEST!: " << mwd.description;
52 // note, we explicitly do not retry here, so that we can detect VINTF
53 // or other bugs (b/151696835)
54 continue;
55 }
56 if (func(mwd)) return true;
57 }
58 return false;
59}
60
Steven Morelandb82b8f82019-10-28 10:52:34 -070061static bool isVintfDeclared(const std::string& name) {
Steven Moreland86a17f82019-09-10 10:18:00 -070062 size_t firstSlash = name.find('/');
63 size_t lastDot = name.rfind('.', firstSlash);
64 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
65 LOG(ERROR) << "VINTF HALs require names in the format type/instance (e.g. "
66 << "some.package.foo.IFoo/default) but got: " << name;
67 return false;
68 }
69 const std::string package = name.substr(0, lastDot);
70 const std::string iface = name.substr(lastDot+1, firstSlash-lastDot-1);
71 const std::string instance = name.substr(firstSlash+1);
72
Steven Moreland2e293aa2020-09-23 00:25:16 +000073 bool found = forEachManifest([&] (const ManifestWithDescription& mwd) {
Steven Moreland2edde8e2020-04-30 17:04:54 -070074 if (mwd.manifest->hasAidlInstance(package, iface, instance)) {
75 LOG(INFO) << "Found " << name << " in " << mwd.description << " VINTF manifest.";
Steven Moreland86a17f82019-09-10 10:18:00 -070076 return true;
77 }
Steven Moreland2e293aa2020-09-23 00:25:16 +000078 return false; // continue
79 });
80
81 if (!found) {
82 // Although it is tested, explicitly rebuilding qualified name, in case it
83 // becomes something unexpected.
84 LOG(ERROR) << "Could not find " << package << "." << iface << "/" << instance
85 << " in the VINTF manifest.";
Steven Moreland86a17f82019-09-10 10:18:00 -070086 }
Steven Moreland2edde8e2020-04-30 17:04:54 -070087
Steven Moreland2e293aa2020-09-23 00:25:16 +000088 return found;
89}
90
91static std::vector<std::string> getVintfInstances(const std::string& interface) {
92 size_t lastDot = interface.rfind('.');
93 if (lastDot == std::string::npos) {
94 LOG(ERROR) << "VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) but got: " << interface;
95 return {};
96 }
97 const std::string package = interface.substr(0, lastDot);
98 const std::string iface = interface.substr(lastDot+1);
99
100 std::vector<std::string> ret;
101 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
102 auto instances = mwd.manifest->getAidlInstances(package, iface);
103 ret.insert(ret.end(), instances.begin(), instances.end());
104 return false; // continue
105 });
106
107 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700108}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700109
110static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
111 if (!Stability::requiresVintfDeclaration(binder)) {
112 return true;
113 }
114
115 return isVintfDeclared(name);
116}
Steven Moreland86a17f82019-09-10 10:18:00 -0700117#endif // !VENDORSERVICEMANAGER
118
Steven Morelandd13f08b2019-11-18 14:23:09 -0800119ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700120// TODO(b/151696835): reenable performance hack when we solve bug, since with
121// this hack and other fixes, it is unlikely we will see even an ephemeral
122// failure when the manifest parse fails. The goal is that the manifest will
123// be read incorrectly and cause the process trying to register a HAL to
124// fail. If this is in fact an early boot kernel contention issue, then we
125// will get no failure, and by its absence, be signalled to invest more
126// effort in re-adding this performance hack.
127// #ifndef VENDORSERVICEMANAGER
128// // can process these at any times, don't want to delay first VINTF client
129// std::thread([] {
130// vintf::VintfObject::GetDeviceHalManifest();
131// vintf::VintfObject::GetFrameworkHalManifest();
132// }).detach();
133// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800134}
Steven Moreland130242d2019-08-26 17:41:32 -0700135ServiceManager::~ServiceManager() {
136 // this should only happen in tests
137
Jon Spivackf288b1d2019-12-19 17:15:51 -0800138 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700139 CHECK(!callbacks.empty()) << name;
140 for (const auto& callback : callbacks) {
141 CHECK(callback != nullptr) << name;
142 }
143 }
144
Steven Moreland130242d2019-08-26 17:41:32 -0700145 for (const auto& [name, service] : mNameToService) {
146 CHECK(service.binder != nullptr) << name;
147 }
148}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700149
150Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700151 *outBinder = tryGetService(name, true);
152 // returns ok regardless of result for legacy reasons
153 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700154}
155
156Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700157 *outBinder = tryGetService(name, false);
158 // returns ok regardless of result for legacy reasons
159 return Status::ok();
160}
161
162sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700163 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700164
Jon Spivack0d844302019-07-22 18:40:34 -0700165 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700166 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700167 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700168 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700169
Jon Spivack9f503a42019-10-22 16:49:19 -0700170 if (!service->allowIsolated) {
Jon Spivack0d844302019-07-22 18:40:34 -0700171 uid_t appid = multiuser_get_app_id(ctx.uid);
172 bool isIsolated = appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700173
Jon Spivack0d844302019-07-22 18:40:34 -0700174 if (isIsolated) {
175 return nullptr;
176 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700177 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700178 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700179 }
180
Steven Morelanda9fe4742019-07-18 14:45:20 -0700181 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700182 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700183 }
184
Jon Spivack0d844302019-07-22 18:40:34 -0700185 if (!out && startIfNotFound) {
186 tryStartService(name);
187 }
188
Jon Spivack9f503a42019-10-22 16:49:19 -0700189 if (out) {
190 // Setting this guarantee each time we hand out a binder ensures that the client-checking
191 // loop knows about the event even if the client immediately drops the service
192 service->guaranteeClient = true;
193 }
194
Jon Spivack0d844302019-07-22 18:40:34 -0700195 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700196}
197
Steven Moreland905e2e82019-07-17 11:05:45 -0700198bool isValidServiceName(const std::string& name) {
199 if (name.size() == 0) return false;
200 if (name.size() > 127) return false;
201
202 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700203 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700204 if (c >= 'a' && c <= 'z') continue;
205 if (c >= 'A' && c <= 'Z') continue;
206 if (c >= '0' && c <= '9') continue;
207 return false;
208 }
209
210 return true;
211}
212
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700213Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700214 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700215
216 // apps cannot add services
217 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
218 return Status::fromExceptionCode(Status::EX_SECURITY);
219 }
220
Steven Morelanda9fe4742019-07-18 14:45:20 -0700221 if (!mAccess->canAdd(ctx, name)) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700222 return Status::fromExceptionCode(Status::EX_SECURITY);
223 }
224
225 if (binder == nullptr) {
226 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
227 }
228
Steven Moreland905e2e82019-07-17 11:05:45 -0700229 if (!isValidServiceName(name)) {
230 LOG(ERROR) << "Invalid service name: " << name;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700231 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
232 }
233
Steven Moreland86a17f82019-09-10 10:18:00 -0700234#ifndef VENDORSERVICEMANAGER
235 if (!meetsDeclarationRequirements(binder, name)) {
236 // already logged
237 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
238 }
239#endif // !VENDORSERVICEMANAGER
240
Steven Moreland88860b02019-08-12 14:24:14 -0700241 // implicitly unlinked when the binder is removed
Steven Moreland46f380b2019-10-16 16:28:21 -0700242 if (binder->remoteBinder() != nullptr && binder->linkToDeath(this) != OK) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700243 LOG(ERROR) << "Could not linkToDeath when adding " << name;
244 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
245 }
246
Devin Moore05ffe522020-08-06 13:58:29 -0700247 // Overwrite the old service if it exists
248 mNameToService[name] = Service {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700249 .binder = binder,
250 .allowIsolated = allowIsolated,
251 .dumpPriority = dumpPriority,
Jon Spivack9f503a42019-10-22 16:49:19 -0700252 .debugPid = ctx.debugPid,
Devin Moore05ffe522020-08-06 13:58:29 -0700253 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700254
Jon Spivackf288b1d2019-12-19 17:15:51 -0800255 auto it = mNameToRegistrationCallback.find(name);
256 if (it != mNameToRegistrationCallback.end()) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700257 for (const sp<IServiceCallback>& cb : it->second) {
Devin Moore05ffe522020-08-06 13:58:29 -0700258 mNameToService[name].guaranteeClient = true;
Steven Moreland27cfab02019-08-12 14:34:16 -0700259 // permission checked in registerForNotifications
260 cb->onRegistration(name, binder);
261 }
262 }
263
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700264 return Status::ok();
265}
266
267Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700268 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700269 return Status::fromExceptionCode(Status::EX_SECURITY);
270 }
271
272 size_t toReserve = 0;
273 for (auto const& [name, service] : mNameToService) {
274 (void) name;
275
276 if (service.dumpPriority & dumpPriority) ++toReserve;
277 }
278
279 CHECK(outList->empty());
280
281 outList->reserve(toReserve);
282 for (auto const& [name, service] : mNameToService) {
283 (void) service;
284
285 if (service.dumpPriority & dumpPriority) {
286 outList->push_back(name);
287 }
288 }
289
290 return Status::ok();
291}
292
Steven Moreland27cfab02019-08-12 14:34:16 -0700293Status ServiceManager::registerForNotifications(
294 const std::string& name, const sp<IServiceCallback>& callback) {
295 auto ctx = mAccess->getCallingContext();
296
297 if (!mAccess->canFind(ctx, name)) {
298 return Status::fromExceptionCode(Status::EX_SECURITY);
299 }
300
301 if (!isValidServiceName(name)) {
302 LOG(ERROR) << "Invalid service name: " << name;
303 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
304 }
305
306 if (callback == nullptr) {
307 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
308 }
309
310 if (OK != IInterface::asBinder(callback)->linkToDeath(this)) {
311 LOG(ERROR) << "Could not linkToDeath when adding " << name;
312 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
313 }
314
Jon Spivackf288b1d2019-12-19 17:15:51 -0800315 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700316
317 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
318 const sp<IBinder>& binder = it->second.binder;
319
320 // never null if an entry exists
321 CHECK(binder != nullptr) << name;
322 callback->onRegistration(name, binder);
323 }
324
325 return Status::ok();
326}
327Status ServiceManager::unregisterForNotifications(
328 const std::string& name, const sp<IServiceCallback>& callback) {
329 auto ctx = mAccess->getCallingContext();
330
331 if (!mAccess->canFind(ctx, name)) {
332 return Status::fromExceptionCode(Status::EX_SECURITY);
333 }
334
335 bool found = false;
336
Jon Spivackf288b1d2019-12-19 17:15:51 -0800337 auto it = mNameToRegistrationCallback.find(name);
338 if (it != mNameToRegistrationCallback.end()) {
339 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700340 }
341
342 if (!found) {
343 LOG(ERROR) << "Trying to unregister callback, but none exists " << name;
344 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
345 }
346
347 return Status::ok();
348}
349
Steven Morelandb82b8f82019-10-28 10:52:34 -0700350Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
351 auto ctx = mAccess->getCallingContext();
352
353 if (!mAccess->canFind(ctx, name)) {
354 return Status::fromExceptionCode(Status::EX_SECURITY);
355 }
356
357 *outReturn = false;
358
359#ifndef VENDORSERVICEMANAGER
360 *outReturn = isVintfDeclared(name);
361#endif
362 return Status::ok();
363}
364
Steven Moreland2e293aa2020-09-23 00:25:16 +0000365binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
366 auto ctx = mAccess->getCallingContext();
367
368 std::vector<std::string> allInstances;
369#ifndef VENDORSERVICEMANAGER
370 allInstances = getVintfInstances(interface);
371#endif
372
373 outReturn->clear();
374
375 for (const std::string& instance : allInstances) {
376 // TODO(b/169275998): allow checking policy only once for the interface
377 if (mAccess->canFind(ctx, interface + "/" + instance)) {
378 outReturn->push_back(instance);
379 }
380 }
381
382 if (outReturn->size() == 0 && allInstances.size() != 0) {
383 return Status::fromExceptionCode(Status::EX_SECURITY);
384 }
385
386 return Status::ok();
387}
388
Jon Spivackf288b1d2019-12-19 17:15:51 -0800389void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
390 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700391 bool* found) {
392 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
393
394 for (auto lit = listeners.begin(); lit != listeners.end();) {
395 if (IInterface::asBinder(*lit) == who) {
396 if(found) *found = true;
397 lit = listeners.erase(lit);
398 } else {
399 ++lit;
400 }
401 }
402
403 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800404 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700405 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800406 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700407 }
408}
409
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700410void ServiceManager::binderDied(const wp<IBinder>& who) {
411 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
412 if (who == it->second.binder) {
413 it = mNameToService.erase(it);
414 } else {
415 ++it;
416 }
417 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700418
Jon Spivackf288b1d2019-12-19 17:15:51 -0800419 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
420 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700421 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700422
423 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
424 removeClientCallback(who, &it);
425 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700426}
427
Jon Spivack0d844302019-07-22 18:40:34 -0700428void ServiceManager::tryStartService(const std::string& name) {
429 ALOGI("Since '%s' could not be found, trying to start it as a lazy AIDL service",
430 name.c_str());
431
432 std::thread([=] {
433 (void)base::SetProperty("ctl.interface_start", "aidl/" + name);
434 }).detach();
435}
436
Jon Spivack9f503a42019-10-22 16:49:19 -0700437Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
438 const sp<IClientCallback>& cb) {
439 if (cb == nullptr) {
440 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
441 }
442
443 auto ctx = mAccess->getCallingContext();
444 if (!mAccess->canAdd(ctx, name)) {
445 return Status::fromExceptionCode(Status::EX_SECURITY);
446 }
447
448 auto serviceIt = mNameToService.find(name);
449 if (serviceIt == mNameToService.end()) {
450 LOG(ERROR) << "Could not add callback for nonexistent service: " << name;
451 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
452 }
453
454 if (serviceIt->second.debugPid != IPCThreadState::self()->getCallingPid()) {
455 LOG(WARNING) << "Only a server can register for client callbacks (for " << name << ")";
456 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
457 }
458
459 if (serviceIt->second.binder != service) {
460 LOG(WARNING) << "Tried to register client callback for " << name
461 << " but a different service is registered under this name.";
462 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
463 }
464
465 if (OK != IInterface::asBinder(cb)->linkToDeath(this)) {
466 LOG(ERROR) << "Could not linkToDeath when adding client callback for " << name;
467 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
468 }
469
470 mNameToClientCallback[name].push_back(cb);
471
472 return Status::ok();
473}
474
475void ServiceManager::removeClientCallback(const wp<IBinder>& who,
476 ClientCallbackMap::iterator* it) {
477 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
478
479 for (auto lit = listeners.begin(); lit != listeners.end();) {
480 if (IInterface::asBinder(*lit) == who) {
481 lit = listeners.erase(lit);
482 } else {
483 ++lit;
484 }
485 }
486
487 if (listeners.empty()) {
488 *it = mNameToClientCallback.erase(*it);
489 } else {
490 (*it)++;
491 }
492}
493
494ssize_t ServiceManager::Service::getNodeStrongRefCount() {
495 sp<BpBinder> bpBinder = binder->remoteBinder();
496 if (bpBinder == nullptr) return -1;
497
498 return ProcessState::self()->getStrongRefCountForNodeByHandle(bpBinder->handle());
499}
500
501void ServiceManager::handleClientCallbacks() {
502 for (const auto& [name, service] : mNameToService) {
Jon Spivackd9533c22020-01-27 22:19:22 +0000503 handleServiceClientCallback(name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700504 }
505}
506
Jon Spivackd9533c22020-01-27 22:19:22 +0000507ssize_t ServiceManager::handleServiceClientCallback(const std::string& serviceName,
508 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700509 auto serviceIt = mNameToService.find(serviceName);
510 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
511 return -1;
512 }
513
514 Service& service = serviceIt->second;
515 ssize_t count = service.getNodeStrongRefCount();
516
517 // binder driver doesn't support this feature
518 if (count == -1) return count;
519
520 bool hasClients = count > 1; // this process holds a strong count
521
522 if (service.guaranteeClient) {
523 // we have no record of this client
524 if (!service.hasClients && !hasClients) {
525 sendClientCallbackNotifications(serviceName, true);
526 }
527
528 // guarantee is temporary
529 service.guaranteeClient = false;
530 }
531
Jon Spivackd9533c22020-01-27 22:19:22 +0000532 // only send notifications if this was called via the interval checking workflow
533 if (isCalledOnInterval) {
534 if (hasClients && !service.hasClients) {
535 // client was retrieved in some other way
536 sendClientCallbackNotifications(serviceName, true);
537 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700538
Jon Spivackd9533c22020-01-27 22:19:22 +0000539 // there are no more clients, but the callback has not been called yet
540 if (!hasClients && service.hasClients) {
541 sendClientCallbackNotifications(serviceName, false);
542 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700543 }
544
545 return count;
546}
547
548void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName, bool hasClients) {
549 auto serviceIt = mNameToService.find(serviceName);
550 if (serviceIt == mNameToService.end()) {
551 LOG(WARNING) << "sendClientCallbackNotifications could not find service " << serviceName;
552 return;
553 }
554 Service& service = serviceIt->second;
555
556 CHECK(hasClients != service.hasClients) << "Record shows: " << service.hasClients
557 << " so we can't tell clients again that we have client: " << hasClients;
558
559 LOG(INFO) << "Notifying " << serviceName << " they have clients: " << hasClients;
560
561 auto ccIt = mNameToClientCallback.find(serviceName);
562 CHECK(ccIt != mNameToClientCallback.end())
563 << "sendClientCallbackNotifications could not find callbacks for service ";
564
565 for (const auto& callback : ccIt->second) {
566 callback->onClients(service.binder, hasClients);
567 }
568
569 service.hasClients = hasClients;
570}
571
572Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
573 if (binder == nullptr) {
574 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
575 }
576
577 auto ctx = mAccess->getCallingContext();
578 if (!mAccess->canAdd(ctx, name)) {
579 return Status::fromExceptionCode(Status::EX_SECURITY);
580 }
581
582 auto serviceIt = mNameToService.find(name);
583 if (serviceIt == mNameToService.end()) {
584 LOG(WARNING) << "Tried to unregister " << name
585 << ", but that service wasn't registered to begin with.";
586 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
587 }
588
589 if (serviceIt->second.debugPid != IPCThreadState::self()->getCallingPid()) {
590 LOG(WARNING) << "Only a server can unregister itself (for " << name << ")";
591 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
592 }
593
594 sp<IBinder> storedBinder = serviceIt->second.binder;
595
596 if (binder != storedBinder) {
597 LOG(WARNING) << "Tried to unregister " << name
598 << ", but a different service is registered under this name.";
599 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
600 }
601
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700602 if (serviceIt->second.guaranteeClient) {
603 LOG(INFO) << "Tried to unregister " << name << ", but there is about to be a client.";
604 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
605 }
606
Jon Spivackd9533c22020-01-27 22:19:22 +0000607 int clients = handleServiceClientCallback(name, false);
Jon Spivack9f503a42019-10-22 16:49:19 -0700608
609 // clients < 0: feature not implemented or other error. Assume clients.
610 // Otherwise:
611 // - kernel driver will hold onto one refcount (during this transaction)
612 // - servicemanager has a refcount (guaranteed by this transaction)
613 // So, if clients > 2, then at least one other service on the system must hold a refcount.
614 if (clients < 0 || clients > 2) {
615 // client callbacks are either disabled or there are other clients
Jon Spivackd9533c22020-01-27 22:19:22 +0000616 LOG(INFO) << "Tried to unregister " << name << ", but there are clients: " << clients;
Jon Spivack620d2dc2020-03-06 13:58:01 -0800617 // Set this flag to ensure the clients are acknowledged in the next callback
618 serviceIt->second.guaranteeClient = true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700619 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
620 }
621
622 mNameToService.erase(name);
623
624 return Status::ok();
625}
626
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700627} // namespace android