blob: d5645a396130135a3fa1c0f19242a577adb9af53 [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 Morelandb9e1cbe2023-02-01 22:44:45 +000042bool is_multiuser_uid_isolated(uid_t uid) {
43 uid_t appid = multiuser_get_app_id(uid);
44 return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
45}
46
Steven Moreland86a17f82019-09-10 10:18:00 -070047#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080048
Steven Moreland2e293aa2020-09-23 00:25:16 +000049struct ManifestWithDescription {
50 std::shared_ptr<const vintf::HalManifest> manifest;
51 const char* description;
52};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080053static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
54#ifdef __ANDROID_RECOVERY__
55 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
56 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000057 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080058 return {};
59 }
60 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
61#else
62 auto vintfObject = vintf::VintfObject::GetInstance();
63 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000064 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080065 return {};
66 }
67 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
68 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
69#endif
70}
71
Steven Moreland2e293aa2020-09-23 00:25:16 +000072// func true -> stop search and forEachManifest will return true
73static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080074 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000075 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000076 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
77 // note, we explicitly do not retry here, so that we can detect VINTF
78 // or other bugs (b/151696835)
79 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000080 }
81 if (func(mwd)) return true;
82 }
83 return false;
84}
85
Steven Morelandedd4e072021-04-21 00:27:29 +000086struct AidlName {
87 std::string package;
88 std::string iface;
89 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070090
Steven Morelandedd4e072021-04-21 00:27:29 +000091 static bool fill(const std::string& name, AidlName* aname) {
92 size_t firstSlash = name.find('/');
93 size_t lastDot = name.rfind('.', firstSlash);
94 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +000095 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
96 "some.package.foo.IFoo/default) but got: %s",
97 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +000098 return false;
99 }
100 aname->package = name.substr(0, lastDot);
101 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
102 aname->instance = name.substr(firstSlash + 1);
103 return true;
104 }
105};
106
107static bool isVintfDeclared(const std::string& name) {
108 AidlName aname;
109 if (!AidlName::fill(name, &aname)) return false;
110
111 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
112 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000113 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000114 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700115 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000116 return false; // continue
117 });
118
119 if (!found) {
120 // Although it is tested, explicitly rebuilding qualified name, in case it
121 // becomes something unexpected.
Pawan Wagh37526162022-09-29 21:55:26 +0000122 ALOGI("Could not find %s.%s/%s in the VINTF manifest.", aname.package.c_str(),
123 aname.iface.c_str(), aname.instance.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700124 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700125
Steven Moreland2e293aa2020-09-23 00:25:16 +0000126 return found;
127}
128
Steven Morelandedd4e072021-04-21 00:27:29 +0000129static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
130 AidlName aname;
131 if (!AidlName::fill(name, &aname)) return std::nullopt;
132
133 std::optional<std::string> updatableViaApex;
134
135 forEachManifest([&](const ManifestWithDescription& mwd) {
136 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
137 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
138 if (manifestInstance.package() != aname.package) return true;
139 if (manifestInstance.interface() != aname.iface) return true;
140 if (manifestInstance.instance() != aname.instance) return true;
141 updatableViaApex = manifestInstance.updatableViaApex();
142 return false; // break (libvintf uses opposite convention)
143 });
Jooyung Hance94b752022-11-14 18:55:06 +0900144 if (updatableViaApex.has_value()) return true; // break (found match)
Steven Morelandedd4e072021-04-21 00:27:29 +0000145 return false; // continue
146 });
147
148 return updatableViaApex;
149}
150
Jooyung Han76944fe2022-10-25 17:02:45 +0900151static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
152 std::vector<std::string> instances;
153
154 forEachManifest([&](const ManifestWithDescription& mwd) {
155 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
156 if (manifestInstance.format() == vintf::HalFormat::AIDL &&
157 manifestInstance.updatableViaApex().has_value() &&
158 manifestInstance.updatableViaApex().value() == apexName) {
159 std::string aname = manifestInstance.package() + "." +
160 manifestInstance.interface() + "/" + manifestInstance.instance();
161 instances.push_back(aname);
162 }
Jooyung Hance94b752022-11-14 18:55:06 +0900163 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900164 });
165 return false; // continue
166 });
167
168 return instances;
169}
170
Devin Moore5e4c2f12021-09-09 22:36:33 +0000171static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
172 AidlName aname;
173 if (!AidlName::fill(name, &aname)) return std::nullopt;
174
175 std::optional<std::string> ip;
176 std::optional<uint64_t> port;
177 forEachManifest([&](const ManifestWithDescription& mwd) {
178 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
179 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
180 if (manifestInstance.package() != aname.package) return true;
181 if (manifestInstance.interface() != aname.iface) return true;
182 if (manifestInstance.instance() != aname.instance) return true;
183 ip = manifestInstance.ip();
184 port = manifestInstance.port();
185 return false; // break (libvintf uses opposite convention)
186 });
187 return false; // continue
188 });
189
190 if (ip.has_value() && port.has_value()) {
191 ConnectionInfo info;
192 info.ipAddress = *ip;
193 info.port = *port;
194 return std::make_optional<ConnectionInfo>(info);
195 } else {
196 return std::nullopt;
197 }
198}
199
Steven Moreland2e293aa2020-09-23 00:25:16 +0000200static std::vector<std::string> getVintfInstances(const std::string& interface) {
201 size_t lastDot = interface.rfind('.');
202 if (lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000203 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
204 "but got: %s",
205 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000206 return {};
207 }
208 const std::string package = interface.substr(0, lastDot);
209 const std::string iface = interface.substr(lastDot+1);
210
211 std::vector<std::string> ret;
212 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
213 auto instances = mwd.manifest->getAidlInstances(package, iface);
214 ret.insert(ret.end(), instances.begin(), instances.end());
215 return false; // continue
216 });
217
218 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700219}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700220
221static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
222 if (!Stability::requiresVintfDeclaration(binder)) {
223 return true;
224 }
225
226 return isVintfDeclared(name);
227}
Steven Moreland86a17f82019-09-10 10:18:00 -0700228#endif // !VENDORSERVICEMANAGER
229
Steven Morelandd13f08b2019-11-18 14:23:09 -0800230ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700231// TODO(b/151696835): reenable performance hack when we solve bug, since with
232// this hack and other fixes, it is unlikely we will see even an ephemeral
233// failure when the manifest parse fails. The goal is that the manifest will
234// be read incorrectly and cause the process trying to register a HAL to
235// fail. If this is in fact an early boot kernel contention issue, then we
236// will get no failure, and by its absence, be signalled to invest more
237// effort in re-adding this performance hack.
238// #ifndef VENDORSERVICEMANAGER
239// // can process these at any times, don't want to delay first VINTF client
240// std::thread([] {
241// vintf::VintfObject::GetDeviceHalManifest();
242// vintf::VintfObject::GetFrameworkHalManifest();
243// }).detach();
244// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800245}
Steven Moreland130242d2019-08-26 17:41:32 -0700246ServiceManager::~ServiceManager() {
247 // this should only happen in tests
248
Jon Spivackf288b1d2019-12-19 17:15:51 -0800249 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700250 CHECK(!callbacks.empty()) << name;
251 for (const auto& callback : callbacks) {
252 CHECK(callback != nullptr) << name;
253 }
254 }
255
Steven Moreland130242d2019-08-26 17:41:32 -0700256 for (const auto& [name, service] : mNameToService) {
257 CHECK(service.binder != nullptr) << name;
258 }
259}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700260
261Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700262 *outBinder = tryGetService(name, true);
263 // returns ok regardless of result for legacy reasons
264 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700265}
266
267Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700268 *outBinder = tryGetService(name, false);
269 // returns ok regardless of result for legacy reasons
270 return Status::ok();
271}
272
273sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700274 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700275
Jon Spivack0d844302019-07-22 18:40:34 -0700276 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700277 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700278 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700279 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700280
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000281 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
282 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700283 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700284 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700285 }
286
Steven Morelanda9fe4742019-07-18 14:45:20 -0700287 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700288 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700289 }
290
Jon Spivack0d844302019-07-22 18:40:34 -0700291 if (!out && startIfNotFound) {
292 tryStartService(name);
293 }
294
Jon Spivack9f503a42019-10-22 16:49:19 -0700295 if (out) {
296 // Setting this guarantee each time we hand out a binder ensures that the client-checking
297 // loop knows about the event even if the client immediately drops the service
298 service->guaranteeClient = true;
299 }
300
Jon Spivack0d844302019-07-22 18:40:34 -0700301 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700302}
303
Steven Moreland905e2e82019-07-17 11:05:45 -0700304bool isValidServiceName(const std::string& name) {
305 if (name.size() == 0) return false;
306 if (name.size() > 127) return false;
307
308 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700309 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700310 if (c >= 'a' && c <= 'z') continue;
311 if (c >= 'A' && c <= 'Z') continue;
312 if (c >= '0' && c <= '9') continue;
313 return false;
314 }
315
316 return true;
317}
318
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700319Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700320 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700321
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700322 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandac2d2852022-03-18 18:15:20 +0000323 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700324 }
325
Steven Morelanda9fe4742019-07-18 14:45:20 -0700326 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandac2d2852022-03-18 18:15:20 +0000327 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denial");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700328 }
329
330 if (binder == nullptr) {
Steven Morelandac2d2852022-03-18 18:15:20 +0000331 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700332 }
333
Steven Moreland905e2e82019-07-17 11:05:45 -0700334 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000335 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandac2d2852022-03-18 18:15:20 +0000336 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700337 }
338
Steven Moreland86a17f82019-09-10 10:18:00 -0700339#ifndef VENDORSERVICEMANAGER
340 if (!meetsDeclarationRequirements(binder, name)) {
341 // already logged
Steven Morelandac2d2852022-03-18 18:15:20 +0000342 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error");
Steven Moreland86a17f82019-09-10 10:18:00 -0700343 }
344#endif // !VENDORSERVICEMANAGER
345
Steven Moreland88860b02019-08-12 14:24:14 -0700346 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000347 if (binder->remoteBinder() != nullptr &&
348 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000349 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandac2d2852022-03-18 18:15:20 +0000350 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "linkToDeath failure");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700351 }
352
Steven Moreland7ee423b2022-09-24 03:52:08 +0000353 auto it = mNameToService.find(name);
354 if (it != mNameToService.end()) {
355 const Service& existing = it->second;
356
357 // We could do better than this because if the other service dies, it
358 // may not have an entry here. However, this case is unlikely. We are
359 // only trying to detect when two different services are accidentally installed.
360
361 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000362 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
363 "from UID %u. Multiple instances installed?",
364 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000365 }
366
367 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000368 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
369 "from SID %s. Multiple instances installed?",
370 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000371 }
372
Pawan Wagh37526162022-09-29 21:55:26 +0000373 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
374 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
375 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000376 }
377
Devin Moore05ffe522020-08-06 13:58:29 -0700378 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000379 mNameToService[name] = Service{
380 .binder = binder,
381 .allowIsolated = allowIsolated,
382 .dumpPriority = dumpPriority,
383 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700384 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700385
Steven Moreland7ee423b2022-09-24 03:52:08 +0000386 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700387 for (const sp<IServiceCallback>& cb : it->second) {
Devin Moore05ffe522020-08-06 13:58:29 -0700388 mNameToService[name].guaranteeClient = true;
Steven Moreland27cfab02019-08-12 14:34:16 -0700389 // permission checked in registerForNotifications
390 cb->onRegistration(name, binder);
391 }
392 }
393
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700394 return Status::ok();
395}
396
397Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700398 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700399 return Status::fromExceptionCode(Status::EX_SECURITY);
400 }
401
402 size_t toReserve = 0;
403 for (auto const& [name, service] : mNameToService) {
404 (void) name;
405
406 if (service.dumpPriority & dumpPriority) ++toReserve;
407 }
408
409 CHECK(outList->empty());
410
411 outList->reserve(toReserve);
412 for (auto const& [name, service] : mNameToService) {
413 (void) service;
414
415 if (service.dumpPriority & dumpPriority) {
416 outList->push_back(name);
417 }
418 }
419
420 return Status::ok();
421}
422
Steven Moreland27cfab02019-08-12 14:34:16 -0700423Status ServiceManager::registerForNotifications(
424 const std::string& name, const sp<IServiceCallback>& callback) {
425 auto ctx = mAccess->getCallingContext();
426
427 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000428 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
429 }
430
431 // note - we could allow isolated apps to get notifications if we
432 // keep track of isolated callbacks and non-isolated callbacks, but
433 // this is done since isolated apps shouldn't access lazy services
434 // so we should be able to use different APIs to keep things simple.
435 // Here, we disallow everything, because the service might not be
436 // registered yet.
437 if (is_multiuser_uid_isolated(ctx.uid)) {
438 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700439 }
440
441 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000442 ALOGE("Invalid service name: %s", name.c_str());
Steven Moreland27cfab02019-08-12 14:34:16 -0700443 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
444 }
445
446 if (callback == nullptr) {
447 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
448 }
449
Steven Morelandb0983182021-04-02 03:14:04 +0000450 if (OK !=
451 IInterface::asBinder(callback)->linkToDeath(
452 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000453 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Moreland27cfab02019-08-12 14:34:16 -0700454 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
455 }
456
Jon Spivackf288b1d2019-12-19 17:15:51 -0800457 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700458
459 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
460 const sp<IBinder>& binder = it->second.binder;
461
462 // never null if an entry exists
463 CHECK(binder != nullptr) << name;
464 callback->onRegistration(name, binder);
465 }
466
467 return Status::ok();
468}
469Status ServiceManager::unregisterForNotifications(
470 const std::string& name, const sp<IServiceCallback>& callback) {
471 auto ctx = mAccess->getCallingContext();
472
473 if (!mAccess->canFind(ctx, name)) {
474 return Status::fromExceptionCode(Status::EX_SECURITY);
475 }
476
477 bool found = false;
478
Jon Spivackf288b1d2019-12-19 17:15:51 -0800479 auto it = mNameToRegistrationCallback.find(name);
480 if (it != mNameToRegistrationCallback.end()) {
481 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700482 }
483
484 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000485 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Moreland27cfab02019-08-12 14:34:16 -0700486 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
487 }
488
489 return Status::ok();
490}
491
Steven Morelandb82b8f82019-10-28 10:52:34 -0700492Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
493 auto ctx = mAccess->getCallingContext();
494
495 if (!mAccess->canFind(ctx, name)) {
496 return Status::fromExceptionCode(Status::EX_SECURITY);
497 }
498
499 *outReturn = false;
500
501#ifndef VENDORSERVICEMANAGER
502 *outReturn = isVintfDeclared(name);
503#endif
504 return Status::ok();
505}
506
Steven Moreland2e293aa2020-09-23 00:25:16 +0000507binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
508 auto ctx = mAccess->getCallingContext();
509
510 std::vector<std::string> allInstances;
511#ifndef VENDORSERVICEMANAGER
512 allInstances = getVintfInstances(interface);
513#endif
514
515 outReturn->clear();
516
517 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000518 if (mAccess->canFind(ctx, interface + "/" + instance)) {
519 outReturn->push_back(instance);
520 }
521 }
522
523 if (outReturn->size() == 0 && allInstances.size() != 0) {
524 return Status::fromExceptionCode(Status::EX_SECURITY);
525 }
526
527 return Status::ok();
528}
529
Steven Morelandedd4e072021-04-21 00:27:29 +0000530Status ServiceManager::updatableViaApex(const std::string& name,
531 std::optional<std::string>* outReturn) {
532 auto ctx = mAccess->getCallingContext();
533
534 if (!mAccess->canFind(ctx, name)) {
535 return Status::fromExceptionCode(Status::EX_SECURITY);
536 }
537
538 *outReturn = std::nullopt;
539
540#ifndef VENDORSERVICEMANAGER
541 *outReturn = getVintfUpdatableApex(name);
542#endif
543 return Status::ok();
544}
545
Jooyung Han76944fe2022-10-25 17:02:45 +0900546Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
547 std::vector<std::string>* outReturn) {
548 auto ctx = mAccess->getCallingContext();
549
550 std::vector<std::string> apexUpdatableInstances;
551#ifndef VENDORSERVICEMANAGER
552 apexUpdatableInstances = getVintfUpdatableInstances(apexName);
553#endif
554
555 outReturn->clear();
556
557 for (const std::string& instance : apexUpdatableInstances) {
558 if (mAccess->canFind(ctx, instance)) {
559 outReturn->push_back(instance);
560 }
561 }
562
563 if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
564 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denial");
565 }
566
567 return Status::ok();
568}
569
Devin Moore5e4c2f12021-09-09 22:36:33 +0000570Status ServiceManager::getConnectionInfo(const std::string& name,
571 std::optional<ConnectionInfo>* outReturn) {
572 auto ctx = mAccess->getCallingContext();
573
574 if (!mAccess->canFind(ctx, name)) {
575 return Status::fromExceptionCode(Status::EX_SECURITY);
576 }
577
578 *outReturn = std::nullopt;
579
580#ifndef VENDORSERVICEMANAGER
581 *outReturn = getVintfConnectionInfo(name);
582#endif
583 return Status::ok();
584}
585
Jon Spivackf288b1d2019-12-19 17:15:51 -0800586void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
587 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700588 bool* found) {
589 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
590
591 for (auto lit = listeners.begin(); lit != listeners.end();) {
592 if (IInterface::asBinder(*lit) == who) {
593 if(found) *found = true;
594 lit = listeners.erase(lit);
595 } else {
596 ++lit;
597 }
598 }
599
600 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800601 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700602 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800603 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700604 }
605}
606
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700607void ServiceManager::binderDied(const wp<IBinder>& who) {
608 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
609 if (who == it->second.binder) {
610 it = mNameToService.erase(it);
611 } else {
612 ++it;
613 }
614 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700615
Jon Spivackf288b1d2019-12-19 17:15:51 -0800616 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
617 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700618 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700619
620 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
621 removeClientCallback(who, &it);
622 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700623}
624
Jon Spivack0d844302019-07-22 18:40:34 -0700625void ServiceManager::tryStartService(const std::string& name) {
Steven Morelandba0f33c2022-11-04 22:24:31 +0000626 ALOGI("Since '%s' could not be found, trying to start it as a lazy AIDL service. (if it's not "
627 "configured to be a lazy service, it may be stuck starting or still starting).",
Jon Spivack0d844302019-07-22 18:40:34 -0700628 name.c_str());
629
630 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000631 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000632 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
633 "this happens when a "
634 "service is not installed, but if the service is intended to be used as a "
635 "lazy service, then it may be configured incorrectly.",
636 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000637 }
Jon Spivack0d844302019-07-22 18:40:34 -0700638 }).detach();
639}
640
Jon Spivack9f503a42019-10-22 16:49:19 -0700641Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
642 const sp<IClientCallback>& cb) {
643 if (cb == nullptr) {
644 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
645 }
646
647 auto ctx = mAccess->getCallingContext();
648 if (!mAccess->canAdd(ctx, name)) {
649 return Status::fromExceptionCode(Status::EX_SECURITY);
650 }
651
652 auto serviceIt = mNameToService.find(name);
653 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000654 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700655 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
656 }
657
Steven Moreland7ee423b2022-09-24 03:52:08 +0000658 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000659 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700660 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
661 }
662
663 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000664 ALOGW("Tried to register client callback for %s but a different service is registered "
665 "under this name.",
666 name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700667 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
668 }
669
Steven Morelandb0983182021-04-02 03:14:04 +0000670 if (OK !=
671 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000672 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700673 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
674 }
675
676 mNameToClientCallback[name].push_back(cb);
677
678 return Status::ok();
679}
680
681void ServiceManager::removeClientCallback(const wp<IBinder>& who,
682 ClientCallbackMap::iterator* it) {
683 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
684
685 for (auto lit = listeners.begin(); lit != listeners.end();) {
686 if (IInterface::asBinder(*lit) == who) {
687 lit = listeners.erase(lit);
688 } else {
689 ++lit;
690 }
691 }
692
693 if (listeners.empty()) {
694 *it = mNameToClientCallback.erase(*it);
695 } else {
696 (*it)++;
697 }
698}
699
700ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000701 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700702 if (bpBinder == nullptr) return -1;
703
Steven Morelande8393882020-12-18 02:27:20 +0000704 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700705}
706
707void ServiceManager::handleClientCallbacks() {
708 for (const auto& [name, service] : mNameToService) {
Jon Spivackd9533c22020-01-27 22:19:22 +0000709 handleServiceClientCallback(name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700710 }
711}
712
Jon Spivackd9533c22020-01-27 22:19:22 +0000713ssize_t ServiceManager::handleServiceClientCallback(const std::string& serviceName,
714 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700715 auto serviceIt = mNameToService.find(serviceName);
716 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
717 return -1;
718 }
719
720 Service& service = serviceIt->second;
721 ssize_t count = service.getNodeStrongRefCount();
722
723 // binder driver doesn't support this feature
724 if (count == -1) return count;
725
726 bool hasClients = count > 1; // this process holds a strong count
727
728 if (service.guaranteeClient) {
729 // we have no record of this client
730 if (!service.hasClients && !hasClients) {
731 sendClientCallbackNotifications(serviceName, true);
732 }
733
734 // guarantee is temporary
735 service.guaranteeClient = false;
736 }
737
Jon Spivackd9533c22020-01-27 22:19:22 +0000738 // only send notifications if this was called via the interval checking workflow
739 if (isCalledOnInterval) {
740 if (hasClients && !service.hasClients) {
741 // client was retrieved in some other way
742 sendClientCallbackNotifications(serviceName, true);
743 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700744
Jon Spivackd9533c22020-01-27 22:19:22 +0000745 // there are no more clients, but the callback has not been called yet
746 if (!hasClients && service.hasClients) {
747 sendClientCallbackNotifications(serviceName, false);
748 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700749 }
750
751 return count;
752}
753
754void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName, bool hasClients) {
755 auto serviceIt = mNameToService.find(serviceName);
756 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000757 ALOGW("sendClientCallbackNotifications could not find service %s", serviceName.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700758 return;
759 }
760 Service& service = serviceIt->second;
761
762 CHECK(hasClients != service.hasClients) << "Record shows: " << service.hasClients
763 << " so we can't tell clients again that we have client: " << hasClients;
764
Pawan Wagh37526162022-09-29 21:55:26 +0000765 ALOGI("Notifying %s they have clients: %d", serviceName.c_str(), hasClients);
Jon Spivack9f503a42019-10-22 16:49:19 -0700766
767 auto ccIt = mNameToClientCallback.find(serviceName);
768 CHECK(ccIt != mNameToClientCallback.end())
769 << "sendClientCallbackNotifications could not find callbacks for service ";
770
771 for (const auto& callback : ccIt->second) {
772 callback->onClients(service.binder, hasClients);
773 }
774
775 service.hasClients = hasClients;
776}
777
778Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
779 if (binder == nullptr) {
780 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
781 }
782
783 auto ctx = mAccess->getCallingContext();
784 if (!mAccess->canAdd(ctx, name)) {
785 return Status::fromExceptionCode(Status::EX_SECURITY);
786 }
787
788 auto serviceIt = mNameToService.find(name);
789 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000790 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
791 name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700792 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
793 }
794
Steven Moreland7ee423b2022-09-24 03:52:08 +0000795 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000796 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700797 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
798 }
799
800 sp<IBinder> storedBinder = serviceIt->second.binder;
801
802 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000803 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
804 name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700805 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
806 }
807
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700808 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000809 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700810 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
811 }
812
Jon Spivackd9533c22020-01-27 22:19:22 +0000813 int clients = handleServiceClientCallback(name, false);
Jon Spivack9f503a42019-10-22 16:49:19 -0700814
815 // clients < 0: feature not implemented or other error. Assume clients.
816 // Otherwise:
817 // - kernel driver will hold onto one refcount (during this transaction)
818 // - servicemanager has a refcount (guaranteed by this transaction)
819 // So, if clients > 2, then at least one other service on the system must hold a refcount.
820 if (clients < 0 || clients > 2) {
821 // client callbacks are either disabled or there are other clients
Pawan Wagh37526162022-09-29 21:55:26 +0000822 ALOGI("Tried to unregister %s, but there are clients: %d", name.c_str(), clients);
Jon Spivack620d2dc2020-03-06 13:58:01 -0800823 // Set this flag to ensure the clients are acknowledged in the next callback
824 serviceIt->second.guaranteeClient = true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700825 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
826 }
827
828 mNameToService.erase(name);
829
830 return Status::ok();
831}
832
Steven Moreland3ea43272021-01-28 22:49:28 +0000833Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
834 if (!mAccess->canList(mAccess->getCallingContext())) {
835 return Status::fromExceptionCode(Status::EX_SECURITY);
836 }
837
838 outReturn->reserve(mNameToService.size());
839 for (auto const& [name, service] : mNameToService) {
840 ServiceDebugInfo info;
841 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000842 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000843
844 outReturn->push_back(std::move(info));
845 }
846
847 return Status::ok();
848}
849
Pawan Wagh243888e2022-09-20 19:37:35 +0000850void ServiceManager::clear() {
851 mNameToService.clear();
852 mNameToRegistrationCallback.clear();
853 mNameToClientCallback.clear();
854}
855
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700856} // namespace android