blob: 7d7433aeb59c74a3f0b24da1d2458c541204523d [file] [log] [blame]
Glenn Kasten44deb052012-02-05 18:09:08 -08001/*
2 * Copyright (C) 2012 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
Eric Laurent9b11c022018-06-06 19:19:22 -070017#define LOG_TAG "ServiceUtilities"
18
Andy Hunga85efab2019-12-23 11:41:29 -080019#include <audio_utils/clock.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070020#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080021#include <binder/IPCThreadState.h>
22#include <binder/IServiceManager.h>
23#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070024#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080025#include <system/audio-hal-enums.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080026
Kevin Rocard8be94972019-02-22 13:26:25 -080027#include <iterator>
28#include <algorithm>
Andy Hunga85efab2019-12-23 11:41:29 -080029#include <pwd.h>
Kevin Rocard8be94972019-02-22 13:26:25 -080030
Svet Ganovbe71aa22015-04-28 12:06:02 -070031/* When performing permission checks we do not use permission cache for
32 * runtime permissions (protection level dangerous) as they may change at
33 * runtime. All other permissions (protection level normal and dangerous)
34 * can be cached as they never change. Of course all permission checked
35 * here are platform defined.
36 */
37
Glenn Kasten44deb052012-02-05 18:09:08 -080038namespace android {
39
Svet Ganov5b81f552018-03-02 09:21:30 -080040static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070041static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
42static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Svet Ganov5b81f552018-03-02 09:21:30 -080043
Svet Ganov5b81f552018-03-02 09:21:30 -080044static String16 resolveCallingPackage(PermissionController& permissionController,
45 const String16& opPackageName, uid_t uid) {
46 if (opPackageName.size() > 0) {
47 return opPackageName;
Svet Ganovbe71aa22015-04-28 12:06:02 -070048 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070049 // In some cases the calling code has no access to the package it runs under.
50 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
51 // case we will get the packages for the calling UID and pick the first one
52 // for attributing the app op. This will work correctly for runtime permissions
53 // as for legacy apps we will toggle the app op for all packages in the UID.
54 // The caveat is that the operation may be attributed to the wrong package and
55 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080056 Vector<String16> packages;
57 permissionController.getPackagesForUid(uid, packages);
58 if (packages.isEmpty()) {
59 ALOGE("No packages for uid %d", uid);
60 return opPackageName; // empty string
61 }
62 return packages[0];
63}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000064
Nate Myrene69cada2020-12-10 10:00:36 -080065static int32_t getOpForSource(audio_source_t source) {
66 switch (source) {
67 case AUDIO_SOURCE_HOTWORD:
68 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
69 case AUDIO_SOURCE_REMOTE_SUBMIX:
70 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
71 case AUDIO_SOURCE_DEFAULT:
72 default:
73 return AppOpsManager::OP_RECORD_AUDIO;
74 }
75}
76
Svet Ganov5b81f552018-03-02 09:21:30 -080077static bool checkRecordingInternal(const String16& opPackageName, pid_t pid,
Nate Myrene69cada2020-12-10 10:00:36 -080078 uid_t uid, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -070079 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -080080 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -070081 // system_server loses its RECORD_AUDIO permission when a secondary
82 // user is active, but it is a core system service so let it through.
83 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Eric Laurent58a0dd82019-10-24 12:42:17 -070084 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +000085
Svet Ganov5b81f552018-03-02 09:21:30 -080086 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
87 // may open a record track on behalf of a client. Note that pid may be a tid.
88 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
89 PermissionController permissionController;
90 const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio, pid, uid);
91 if (!ok) {
92 ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str());
93 return false;
94 }
95
96 String16 resolvedOpPackageName = resolveCallingPackage(
97 permissionController, opPackageName, uid);
98 if (resolvedOpPackageName.size() == 0) {
99 return false;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700100 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000101
102 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800103 const int32_t op = getOpForSource(source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800104 if (start) {
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000105 if (int32_t mode = appOps.startOpNoThrow(
106 op, uid, resolvedOpPackageName, /*startIfModeDefault*/ false);
107 mode != AppOpsManager::MODE_ALLOWED) {
108 ALOGE("Request start for \"%s\" (uid %d) denied by app op: %d, mode: %d",
109 String8(resolvedOpPackageName).c_str(), uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800110 return false;
111 }
112 } else {
Narayan Kamathbf85d8b2020-08-20 17:19:57 +0100113 // Always use OP_RECORD_AUDIO for checks at creation time.
Nate Myrene69cada2020-12-10 10:00:36 -0800114 if (int32_t mode = appOps.checkOp(op, uid, resolvedOpPackageName);
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000115 mode != AppOpsManager::MODE_ALLOWED) {
116 ALOGE("Request check for \"%s\" (uid %d) denied by app op: %d, mode: %d",
Nate Myrene69cada2020-12-10 10:00:36 -0800117 String8(resolvedOpPackageName).c_str(), uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800118 return false;
119 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000120 }
121
122 return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800123}
124
Svet Ganov5b81f552018-03-02 09:21:30 -0800125bool recordingAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
Nate Myrene69cada2020-12-10 10:00:36 -0800126 return checkRecordingInternal(opPackageName, pid, uid, /*start*/ false, AUDIO_SOURCE_DEFAULT);
Svet Ganov5b81f552018-03-02 09:21:30 -0800127}
128
Nate Myrene69cada2020-12-10 10:00:36 -0800129bool startRecording(const String16& opPackageName, pid_t pid, uid_t uid, audio_source_t source) {
130 return checkRecordingInternal(opPackageName, pid, uid, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800131}
132
Nate Myrene69cada2020-12-10 10:00:36 -0800133void finishRecording(const String16& opPackageName, uid_t uid, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800134 // Okay to not track in app ops as audio server is us and if
135 // device is rooted security model is considered compromised.
Andy Hung4ef19fa2018-05-15 19:35:29 -0700136 if (isAudioServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800137
138 PermissionController permissionController;
139 String16 resolvedOpPackageName = resolveCallingPackage(
140 permissionController, opPackageName, uid);
141 if (resolvedOpPackageName.size() == 0) {
142 return;
143 }
144
145 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800146
147 const int32_t op = getOpForSource(source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800148 appOps.finishOp(op, uid, resolvedOpPackageName);
149}
150
Eric Laurentb2379ba2016-05-23 17:42:12 -0700151bool captureAudioOutputAllowed(pid_t pid, uid_t uid) {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700152 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700153 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800154 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700155 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700156 return ok;
157}
158
Kevin Rocard36b17552019-03-07 18:48:07 -0800159bool captureMediaOutputAllowed(pid_t pid, uid_t uid) {
160 if (isAudioServerOrRootUid(uid)) return true;
161 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
162 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
163 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
164 return ok;
165}
166
Hayden Gomesb7429922020-12-11 13:59:18 -0800167bool captureTunerAudioInputAllowed(pid_t pid, uid_t uid) {
168 if (isAudioServerOrRootUid(uid)) return true;
169 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
170 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
171 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
172 return ok;
173}
174
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200175bool captureVoiceCommunicationOutputAllowed(pid_t pid, uid_t uid) {
176 if (isAudioServerOrRootUid(uid)) return true;
177 static const String16 sCaptureVoiceCommOutput(
178 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
179 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
180 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
181 return ok;
182}
183
jiabin68e0df72019-03-18 17:55:35 -0700184bool captureHotwordAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700185 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
jiabin68e0df72019-03-18 17:55:35 -0700186 bool ok = recordingAllowed(opPackageName, pid, uid);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700187
188 if (ok) {
189 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
190 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
jiabin68e0df72019-03-18 17:55:35 -0700191 ok = PermissionCache::checkPermission(sCaptureHotwordAllowed, pid, uid);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700192 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700193 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700194 return ok;
195}
196
Glenn Kasten44deb052012-02-05 18:09:08 -0800197bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700198 // given this is a permission check, could this be isAudioServerOrRootUid()?
199 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800200 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700201 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
202 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800203 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
204 return ok;
205}
206
Eric Laurent5284ed52014-05-29 14:37:38 -0700207bool modifyAudioRoutingAllowed() {
Eric Laurent8a1095a2019-11-08 14:44:16 -0800208 return modifyAudioRoutingAllowed(
209 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
210}
211
212bool modifyAudioRoutingAllowed(pid_t pid, uid_t uid) {
213 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700214 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800215 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
216 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
217 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700218 return ok;
219}
220
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700221bool modifyDefaultAudioEffectsAllowed() {
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800222 return modifyDefaultAudioEffectsAllowed(
223 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
224}
225
226bool modifyDefaultAudioEffectsAllowed(pid_t pid, uid_t uid) {
227 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
228
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700229 static const String16 sModifyDefaultAudioEffectsAllowed(
230 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
231 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800232 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
233 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
234 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700235 return ok;
236}
237
Glenn Kasten44deb052012-02-05 18:09:08 -0800238bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800239 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700240 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800241 bool ok = PermissionCache::checkCallingPermission(sDump);
242 // convention is for caller to dump an error message to fd instead of logging here
243 //if (!ok) ALOGE("Request requires android.permission.DUMP");
244 return ok;
245}
246
Nadav Bar766fb022018-01-07 12:18:03 +0200247bool modifyPhoneStateAllowed(pid_t pid, uid_t uid) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800248 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700249 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
250 return ok;
251}
252
253// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
254bool bypassInterruptionPolicyAllowed(pid_t pid, uid_t uid) {
255 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
256 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
257 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
258 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
259 ALOGE_IF(!ok, "Request requires %s or %s",
260 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200261 return ok;
262}
263
Eric Laurent9b11c022018-06-06 19:19:22 -0700264status_t checkIMemory(const sp<IMemory>& iMemory)
265{
266 if (iMemory == 0) {
267 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
268 return BAD_VALUE;
269 }
270
271 sp<IMemoryHeap> heap = iMemory->getMemory();
272 if (heap == 0) {
273 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
274 return BAD_VALUE;
275 }
276
277 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
278 lseek(heap->getHeapID(), 0, SEEK_SET);
279
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700280 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700281 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700282 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700283 return BAD_VALUE;
284 }
285
286 return NO_ERROR;
287}
288
Ricardo Correa57a37692020-03-23 17:27:25 -0700289sp<content::pm::IPackageManagerNative> MediaPackageManager::retreivePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800290 const sp<IServiceManager> sm = defaultServiceManager();
291 if (sm == nullptr) {
292 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700293 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800294 }
295 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
296 if (packageManager == nullptr) {
297 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700298 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800299 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700300 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800301}
302
303std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
304 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700305 /** Can not fetch package manager at construction it may not yet be registered. */
306 mPackageManager = retreivePackageManager();
307 if (mPackageManager == nullptr) {
308 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
309 return std::nullopt;
310 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800311 }
312
313 std::vector<std::string> packageNames;
314 auto status = mPackageManager->getNamesForUids({(int32_t)uid}, &packageNames);
315 if (!status.isOk()) {
316 ALOGW("%s: Playback capture is denied for uid %u as the package names could not be "
317 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
318 return std::nullopt;
319 }
320 if (packageNames.empty()) {
321 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
322 "from the package manager: %s", __func__, uid, status.toString8().c_str());
323 return std::nullopt;
324 }
325 std::vector<bool> isAllowed;
326 status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
327 if (!status.isOk()) {
328 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
329 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
330 return std::nullopt;
331 }
332 if (packageNames.size() != isAllowed.size()) {
333 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
334 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
335 return std::nullopt;
336 }
337
338 // Zip together packageNames and isAllowed for debug logs
339 Packages& packages = mDebugLog[uid];
340 packages.resize(packageNames.size()); // Reuse all objects
341 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
342 begin(packages), [] (auto& name, bool isAllowed) -> Package {
343 return {std::move(name), isAllowed};
344 });
345
346 // Only allow playback record if all packages in this UID allow it
347 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
348 [](bool b) { return b; });
349
350 return playbackCaptureAllowed;
351}
352
353void MediaPackageManager::dump(int fd, int spaces) const {
354 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
355 if (mPackageManager == nullptr) {
356 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
357 }
358 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
359
360 for (const auto& uidCache : mDebugLog) {
361 for (const auto& package : std::get<Packages>(uidCache)) {
362 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
363 std::get<const uid_t>(uidCache),
364 package.playbackCaptureAllowed ? "true " : "false",
365 package.name.c_str());
366 }
367 }
368}
369
Andy Hunga85efab2019-12-23 11:41:29 -0800370// How long we hold info before we re-fetch it (24 hours) if we found it previously.
371static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
372// Maximum info records we retain before clearing everything.
373static constexpr size_t INFO_CACHE_MAX = 1000;
374
375// The original code is from MediaMetricsService.cpp.
376mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
377{
378 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
379 struct mediautils::UidInfo::Info info;
380 {
381 std::lock_guard _l(mLock);
382 auto it = mInfoMap.find(uid);
383 if (it != mInfoMap.end()) {
384 info = it->second;
385 ALOGV("%s: uid %d expiration %lld now %lld",
386 __func__, uid, (long long)info.expirationNs, (long long)now);
387 if (info.expirationNs <= now) {
388 // purge the stale entry and fall into re-fetching
389 ALOGV("%s: entry for uid %d expired, now %lld",
390 __func__, uid, (long long)now);
391 mInfoMap.erase(it);
392 info.uid = (uid_t)-1; // this is always fully overwritten
393 }
394 }
395 }
396
397 // if we did not find it in our map, look it up
398 if (info.uid == (uid_t)(-1)) {
399 sp<IServiceManager> sm = defaultServiceManager();
400 sp<content::pm::IPackageManagerNative> package_mgr;
401 if (sm.get() == nullptr) {
402 ALOGE("%s: Cannot find service manager", __func__);
403 } else {
404 sp<IBinder> binder = sm->getService(String16("package_native"));
405 if (binder.get() == nullptr) {
406 ALOGE("%s: Cannot find package_native", __func__);
407 } else {
408 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
409 }
410 }
411
412 // find package name
413 std::string pkg;
414 if (package_mgr != nullptr) {
415 std::vector<std::string> names;
416 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
417 if (!status.isOk()) {
418 ALOGE("%s: getNamesForUids failed: %s",
419 __func__, status.exceptionMessage().c_str());
420 } else {
421 if (!names[0].empty()) {
422 pkg = names[0].c_str();
423 }
424 }
425 }
426
427 if (pkg.empty()) {
428 struct passwd pw{}, *result;
429 char buf[8192]; // extra buffer space - should exceed what is
430 // required in struct passwd_pw (tested),
431 // and even then this is only used in backup
432 // when the package manager is unavailable.
433 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
434 && result != nullptr
435 && result->pw_name != nullptr) {
436 pkg = result->pw_name;
437 }
438 }
439
440 // strip any leading "shared:" strings that came back
441 if (pkg.compare(0, 7, "shared:") == 0) {
442 pkg.erase(0, 7);
443 }
444
445 // determine how pkg was installed and the versionCode
446 std::string installer;
447 int64_t versionCode = 0;
448 bool notFound = false;
449 if (pkg.empty()) {
450 pkg = std::to_string(uid); // not found
451 notFound = true;
452 } else if (strchr(pkg.c_str(), '.') == nullptr) {
453 // not of form 'com.whatever...'; assume internal
454 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800455 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
456 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800457 } else if (package_mgr.get() != nullptr) {
458 String16 pkgName16(pkg.c_str());
459 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
460 if (!status.isOk()) {
461 ALOGE("%s: getInstallerForPackage failed: %s",
462 __func__, status.exceptionMessage().c_str());
463 }
464
465 // skip if we didn't get an installer
466 if (status.isOk()) {
467 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
468 if (!status.isOk()) {
469 ALOGE("%s: getVersionCodeForPackage failed: %s",
470 __func__, status.exceptionMessage().c_str());
471 }
472 }
473
474 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
475 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
476 }
477
478 // add it to the map, to save a subsequent lookup
479 std::lock_guard _l(mLock);
480 // first clear if we have too many cached elements. This would be rare.
481 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
482
483 // always overwrite
484 info.uid = uid;
485 info.package = std::move(pkg);
486 info.installer = std::move(installer);
487 info.versionCode = versionCode;
488 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
489 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
490 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
491 mInfoMap[uid] = info;
492 }
493 return info;
494}
495
Glenn Kasten44deb052012-02-05 18:09:08 -0800496} // namespace android