blob: 8ceff968881bab92c5bfbebb1a3735facbd2c4f2 [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
guochuang0c55eae2024-03-08 19:42:54 +080017//#define LOG_NDEBUG 0
Eric Laurent9b11c022018-06-06 19:19:22 -070018#define LOG_TAG "ServiceUtilities"
19
Andy Hunga85efab2019-12-23 11:41:29 -080020#include <audio_utils/clock.h>
Atneya Nair23348762024-10-14 14:16:06 -070021#include <android-base/properties.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070022#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080023#include <binder/IPCThreadState.h>
24#include <binder/IServiceManager.h>
25#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070026#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080027#include <system/audio-hal-enums.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070028#include <media/AidlConversion.h>
29#include <media/AidlConversionUtil.h>
Svet Ganov33761132021-05-13 22:51:08 +000030#include <android/content/AttributionSourceState.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080031
Chaitanya Cheemala (xWF)e1dfc0f2024-10-08 09:41:45 +000032#include <algorithm>
Atneya Nair23348762024-10-14 14:16:06 -070033#include <iterator>
34#include <mutex>
Andy Hunga85efab2019-12-23 11:41:29 -080035#include <pwd.h>
Atneya Nair23348762024-10-14 14:16:06 -070036#include <thread>
Kevin Rocard8be94972019-02-22 13:26:25 -080037
Svet Ganovbe71aa22015-04-28 12:06:02 -070038/* When performing permission checks we do not use permission cache for
39 * runtime permissions (protection level dangerous) as they may change at
40 * runtime. All other permissions (protection level normal and dangerous)
41 * can be cached as they never change. Of course all permission checked
42 * here are platform defined.
43 */
44
Glenn Kasten44deb052012-02-05 18:09:08 -080045namespace android {
46
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000047namespace {
Atneya Nair38558e12024-10-25 17:59:36 -070048constexpr auto PERMISSION_GRANTED = permission::PermissionChecker::PERMISSION_GRANTED;
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000049constexpr auto PERMISSION_HARD_DENIED = permission::PermissionChecker::PERMISSION_HARD_DENIED;
50}
51
Svet Ganov33761132021-05-13 22:51:08 +000052using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070053
Svet Ganov5b81f552018-03-02 09:21:30 -080054static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070055static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
56static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Eric Laurentb0eff0f2021-11-09 16:05:49 +010057static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
jiabin7616b332024-11-20 04:47:02 +000058static const String16 sModifyAudioSettingsPrivileged(
59 "android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED");
Svet Ganov5b81f552018-03-02 09:21:30 -080060
Svet Ganov5b81f552018-03-02 09:21:30 -080061static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062 const std::optional<String16> opPackageName, uid_t uid) {
63 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
64 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070065 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070066 // In some cases the calling code has no access to the package it runs under.
67 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
68 // case we will get the packages for the calling UID and pick the first one
69 // for attributing the app op. This will work correctly for runtime permissions
70 // as for legacy apps we will toggle the app op for all packages in the UID.
71 // The caveat is that the operation may be attributed to the wrong package and
72 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080073 Vector<String16> packages;
74 permissionController.getPackagesForUid(uid, packages);
75 if (packages.isEmpty()) {
76 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070077 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080078 }
79 return packages[0];
80}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000081
Atneya Nair89ff0432024-11-19 12:47:28 -080082// NOTE/TODO(b/379754682):
83// AUDIO_SOURCE_VOICE_DOWNLINK and AUDIO_SOURCE_VOICE_CALL are handled specially:
84// DOWNLINK is an output source, but we still require RecordOp in addition to
85// OP_RECORD_INCOMING_PHONE_AUDIO
86// CALL includes both uplink and downlink, but we attribute RECORD_OP (only), since
87// there is not support for noting multiple ops.
Eric Laurent45e16b92021-05-20 11:10:47 +020088int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080089 switch (source) {
Atneya Nair89ff0432024-11-19 12:47:28 -080090 // BEGIN output sources
Atneya Nair38558e12024-10-25 17:59:36 -070091 case AUDIO_SOURCE_FM_TUNER:
92 return AppOpsManager::OP_NONE;
Mickey Keeley90d657d2021-10-20 18:06:38 -070093 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080094 case AUDIO_SOURCE_REMOTE_SUBMIX:
Atneya Nair89ff0432024-11-19 12:47:28 -080095 // TODO -- valid in all cases?
Nate Myrene69cada2020-12-10 10:00:36 -080096 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070097 case AUDIO_SOURCE_VOICE_DOWNLINK:
98 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Atneya Nair89ff0432024-11-19 12:47:28 -080099 // END output sources
Atneya Nair38558e12024-10-25 17:59:36 -0700100 case AUDIO_SOURCE_HOTWORD:
101 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Nate Myrene69cada2020-12-10 10:00:36 -0800102 case AUDIO_SOURCE_DEFAULT:
103 default:
104 return AppOpsManager::OP_RECORD_AUDIO;
105 }
106}
107
Atneya Nair38558e12024-10-25 17:59:36 -0700108bool isRecordOpRequired(audio_source_t source) {
109 switch (source) {
110 case AUDIO_SOURCE_FM_TUNER:
111 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
112 case AUDIO_SOURCE_REMOTE_SUBMIX:
Atneya Nair89ff0432024-11-19 12:47:28 -0800113 // case AUDIO_SOURCE_VOICE_DOWNLINK:
Atneya Nair38558e12024-10-25 17:59:36 -0700114 return false;
115 default:
116 return true;
117 }
118}
119
Svet Ganov33761132021-05-13 22:51:08 +0000120std::optional<AttributionSourceState> resolveAttributionSource(
Marvin Raminb03b49f2024-04-04 16:25:31 +0200121 const AttributionSourceState& callerAttributionSource, const uint32_t virtualDeviceId) {
Svet Ganov33761132021-05-13 22:51:08 +0000122 AttributionSourceState nextAttributionSource = callerAttributionSource;
123
124 if (!nextAttributionSource.packageName.has_value()) {
125 nextAttributionSource = AttributionSourceState(nextAttributionSource);
126 PermissionController permissionController;
127 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
128 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
129 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
130 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
131 uid)));
132 if (!nextAttributionSource.packageName.has_value()) {
133 return std::nullopt;
134 }
135 }
Marvin Raminb03b49f2024-04-04 16:25:31 +0200136 nextAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000137
138 AttributionSourceState myAttributionSource;
139 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
140 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Nate Myrene84d6912022-11-10 14:09:34 -0800141 // Create a static token for audioserver requests, which identifies the
142 // audioserver to the app ops system
143 static sp<BBinder> appOpsToken = sp<BBinder>::make();
144 myAttributionSource.token = appOpsToken;
Marvin Raminb03b49f2024-04-04 16:25:31 +0200145 myAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000146 myAttributionSource.next.push_back(nextAttributionSource);
147
148 return std::optional<AttributionSourceState>{myAttributionSource};
149}
150
Atneya Nair38558e12024-10-25 17:59:36 -0700151
152static int checkRecordingInternal(const AttributionSourceState &attributionSource,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100153 const uint32_t virtualDeviceId,
154 const String16 &msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700155 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800156 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700157 // system_server loses its RECORD_AUDIO permission when a secondary
158 // user is active, but it is a core system service so let it through.
159 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000160 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Atneya Nair38558e12024-10-25 17:59:36 -0700161 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return PERMISSION_GRANTED;
Svet Ganov5b81f552018-03-02 09:21:30 -0800162
Svet Ganov33761132021-05-13 22:51:08 +0000163 const int32_t attributedOpCode = getOpForSource(source);
Atneya Nair38558e12024-10-25 17:59:36 -0700164 if (isRecordOpRequired(source)) {
165 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
166 // may open a record track on behalf of a client. Note that pid may be a tid.
167 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
168 std::optional<AttributionSourceState> resolvedAttributionSource =
169 resolveAttributionSource(attributionSource, virtualDeviceId);
170 if (!resolvedAttributionSource.has_value()) {
171 return PERMISSION_HARD_DENIED;
172 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000173
Atneya Nair38558e12024-10-25 17:59:36 -0700174 permission::PermissionChecker permissionChecker;
175 int permitted;
176 if (start) {
177 permitted = permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
178 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
179 attributedOpCode);
180 } else {
181 permitted = permissionChecker.checkPermissionForPreflightFromDatasource(
182 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
183 attributedOpCode);
184 }
185
186 return permitted;
Svet Ganov5b81f552018-03-02 09:21:30 -0800187 } else {
Atneya Nair38558e12024-10-25 17:59:36 -0700188 if (attributedOpCode == AppOpsManager::OP_NONE) return PERMISSION_GRANTED; // nothing to do
189 AppOpsManager ap{};
190 PermissionController pc{};
191 return ap.startOpNoThrow(
192 attributedOpCode, attributionSource.uid,
193 resolveCallingPackage(pc,
194 String16{attributionSource.packageName.value_or("").c_str()},
195 attributionSource.uid),
196 false,
197 attributionSource.attributionTag.has_value()
198 ? String16{attributionSource.attributionTag.value().c_str()}
199 : String16{},
200 msg);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000201 }
Glenn Kasten44deb052012-02-05 18:09:08 -0800202}
203
Marvin Ramine5a122d2023-12-07 13:57:59 +0100204static constexpr int DEVICE_ID_DEFAULT = 0;
205
206bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
207 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000208 source) != PERMISSION_HARD_DENIED;
Marvin Ramine5a122d2023-12-07 13:57:59 +0100209}
210
211bool recordingAllowed(const AttributionSourceState &attributionSource,
212 const uint32_t virtualDeviceId,
213 audio_source_t source) {
214 return checkRecordingInternal(attributionSource, virtualDeviceId,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000215 String16(), /*start*/ false, source) != PERMISSION_HARD_DENIED;
Svet Ganov5b81f552018-03-02 09:21:30 -0800216}
217
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000218int startRecording(const AttributionSourceState& attributionSource,
Marvin Raminb03b49f2024-04-04 16:25:31 +0200219 const uint32_t virtualDeviceId,
220 const String16& msg,
221 audio_source_t source) {
222 return checkRecordingInternal(attributionSource, virtualDeviceId, msg, /*start*/ true,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100223 source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800224}
225
Marvin Raminb03b49f2024-04-04 16:25:31 +0200226void finishRecording(const AttributionSourceState &attributionSource, uint32_t virtualDeviceId,
227 audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800228 // Okay to not track in app ops as audio server is us and if
229 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000230 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
231 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800232
Svet Ganov33761132021-05-13 22:51:08 +0000233 const int32_t attributedOpCode = getOpForSource(source);
Atneya Nair38558e12024-10-25 17:59:36 -0700234 if (isRecordOpRequired(source)) {
235 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
236 // may open a record track on behalf of a client. Note that pid may be a tid.
237 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
238 const std::optional<AttributionSourceState> resolvedAttributionSource =
239 resolveAttributionSource(attributionSource, virtualDeviceId);
240 if (!resolvedAttributionSource.has_value()) {
241 return;
242 }
243
244 permission::PermissionChecker permissionChecker;
245 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
246 resolvedAttributionSource.value());
247 } else {
248 if (attributedOpCode == AppOpsManager::OP_NONE) return; // nothing to do
249 AppOpsManager ap{};
250 PermissionController pc{};
251 ap.finishOp(attributedOpCode, attributionSource.uid,
252 resolveCallingPackage(
253 pc, String16{attributionSource.packageName.value_or("").c_str()},
254 attributionSource.uid),
255 attributionSource.attributionTag.has_value()
256 ? String16{attributionSource.attributionTag.value().c_str()}
257 : String16{});
258 }
Svet Ganov5b81f552018-03-02 09:21:30 -0800259}
260
Svet Ganov33761132021-05-13 22:51:08 +0000261bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
262 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700263 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700264 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
lpeter20d2e032022-06-01 19:38:44 +0800265 // Use PermissionChecker, which includes some logic for allowing the isolated
266 // HotwordDetectionService to hold certain permissions.
267 permission::PermissionChecker permissionChecker;
268 bool ok = (permissionChecker.checkPermissionForPreflight(
269 sCaptureAudioOutput, attributionSource, String16(),
270 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700271 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700272 return ok;
273}
274
Svet Ganov33761132021-05-13 22:51:08 +0000275bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
276 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
277 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800278 if (isAudioServerOrRootUid(uid)) return true;
279 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
280 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
281 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
282 return ok;
283}
284
Svet Ganov33761132021-05-13 22:51:08 +0000285bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
286 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
287 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800288 if (isAudioServerOrRootUid(uid)) return true;
289 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
290 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
291 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
292 return ok;
293}
294
Svet Ganov33761132021-05-13 22:51:08 +0000295bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
296 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
297 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200298 if (isAudioServerOrRootUid(uid)) return true;
299 static const String16 sCaptureVoiceCommOutput(
300 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
301 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
302 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
303 return ok;
304}
305
Eric Laurentdbb80322024-11-18 16:09:51 -0800306bool bypassConcurrentPolicyAllowed(const AttributionSourceState& attributionSource) {
307 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
308 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
309 if (isAudioServerOrRootUid(uid)) return true;
310 static const String16 sBypassConcurrentPolicy(
311 "android.permission.BYPASS_CONCURRENT_RECORD_AUDIO_RESTRICTION ");
312 // Use PermissionChecker, which includes some logic for allowing the isolated
313 // HotwordDetectionService to hold certain permissions.
314 bool ok = PermissionCache::checkPermission(sBypassConcurrentPolicy, pid, uid);
315 if (!ok) {
316 ALOGV("Request requires android.permission.BYPASS_CONCURRENT_RECORD_AUDIO_RESTRICTION");
317 }
318 return ok;
319}
320
Carter Hsua3abb402021-10-26 11:11:20 +0800321bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
322 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
323 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
324 if (isAudioServerOrRootUid(uid)) return true;
325 static const String16 sAccessUltrasound(
326 "android.permission.ACCESS_ULTRASOUND");
327 bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
328 if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
329 return ok;
330}
331
Svet Ganov33761132021-05-13 22:51:08 +0000332bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700333 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000334 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700335
336 if (ok) {
337 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700338 // Use PermissionChecker, which includes some logic for allowing the isolated
339 // HotwordDetectionService to hold certain permissions.
340 permission::PermissionChecker permissionChecker;
341 ok = (permissionChecker.checkPermissionForPreflight(
342 sCaptureHotwordAllowed, attributionSource, String16(),
343 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700344 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700345 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700346 return ok;
347}
348
Glenn Kasten44deb052012-02-05 18:09:08 -0800349bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700350 // given this is a permission check, could this be isAudioServerOrRootUid()?
351 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800352 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700353 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
354 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800355 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
356 return ok;
357}
358
Eric Laurent5284ed52014-05-29 14:37:38 -0700359bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000360 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800361}
362
Svet Ganov33761132021-05-13 22:51:08 +0000363bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
364 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
365 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Atneya Nairb7199082024-08-17 19:04:46 -0700366 if (isAudioServerUid(uid)) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700367 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800368 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
369 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
370 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700371 return ok;
372}
373
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700374bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000375 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800376}
377
Svet Ganov33761132021-05-13 22:51:08 +0000378bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
379 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
380 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Atneya Nairb7199082024-08-17 19:04:46 -0700381 if (isAudioServerUid(uid)) return true;
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800382
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700383 static const String16 sModifyDefaultAudioEffectsAllowed(
384 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
385 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800386 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
387 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
388 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700389 return ok;
390}
391
jiabin7616b332024-11-20 04:47:02 +0000392bool modifyAudioSettingsPrivilegedAllowed(const AttributionSourceState& attributionSource) {
393 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
394 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
395 if (isAudioServerUid(uid)) return true;
396 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
397 bool ok = PermissionCache::checkPermission(sModifyAudioSettingsPrivileged, pid, uid);
398 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED denied for uid %d",
399 __func__, uid);
400 return ok;
401}
402
Glenn Kasten44deb052012-02-05 18:09:08 -0800403bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800404 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700405 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800406 bool ok = PermissionCache::checkCallingPermission(sDump);
407 // convention is for caller to dump an error message to fd instead of logging here
408 //if (!ok) ALOGE("Request requires android.permission.DUMP");
409 return ok;
410}
411
Svet Ganov33761132021-05-13 22:51:08 +0000412bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
413 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
414 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800415 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700416 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
417 return ok;
418}
419
420// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000421bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
422 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
423 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700424 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
425 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
426 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
427 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
428 ALOGE_IF(!ok, "Request requires %s or %s",
429 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200430 return ok;
431}
432
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100433bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
434 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
435 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
436
437 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
438 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
Eric Laurenta6244a02021-12-14 14:05:25 +0100439 if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100440 __func__, uid);
441 return ok;
442}
443
Svet Ganov33761132021-05-13 22:51:08 +0000444AttributionSourceState getCallingAttributionSource() {
445 AttributionSourceState attributionSource = AttributionSourceState();
446 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
447 IPCThreadState::self()->getCallingPid()));
448 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
449 IPCThreadState::self()->getCallingUid()));
450 attributionSource.token = sp<BBinder>::make();
451 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700452}
453
Eric Laurent269acb42021-04-23 16:53:22 +0200454void purgePermissionCache() {
455 PermissionCache::purgeCache();
456}
457
Eric Laurent9b11c022018-06-06 19:19:22 -0700458status_t checkIMemory(const sp<IMemory>& iMemory)
459{
460 if (iMemory == 0) {
461 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
462 return BAD_VALUE;
463 }
464
465 sp<IMemoryHeap> heap = iMemory->getMemory();
466 if (heap == 0) {
467 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
468 return BAD_VALUE;
469 }
470
471 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
472 lseek(heap->getHeapID(), 0, SEEK_SET);
473
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700474 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700475 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700476 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700477 return BAD_VALUE;
478 }
479
480 return NO_ERROR;
481}
482
Atneya Nair23348762024-10-14 14:16:06 -0700483// TODO(b/285588444), clean this up on main, but soak it for backporting purposes for now
484namespace {
485class BluetoothPermissionCache {
486 static constexpr auto SYSPROP_NAME = "cache_key.system_server.package_info";
487 const String16 BLUETOOTH_PERM {"android.permission.BLUETOOTH_CONNECT"};
488 mutable std::mutex mLock;
489 // Cached property conditionally defined, since only avail on bionic. On host, don't inval cache
490#if defined(__BIONIC__)
491 // Unlocked, but only accessed from mListenerThread
492 base::CachedProperty mCachedProperty;
493#endif
494 // This thread is designed to never join/terminate, so no signal is fine
495 const std::thread mListenerThread;
496 GUARDED_BY(mLock)
497 std::string mPropValue;
498 GUARDED_BY(mLock)
499 std::unordered_map<uid_t, bool> mCache;
500 PermissionController mPc{};
501public:
502 BluetoothPermissionCache()
503#if defined(__BIONIC__)
504 : mCachedProperty{SYSPROP_NAME},
505 mListenerThread([this]() mutable {
506 while (true) {
507 std::string newVal = mCachedProperty.WaitForChange() ?: "";
508 std::lock_guard l{mLock};
509 if (newVal != mPropValue) {
510 ALOGV("Bluetooth permission update");
511 mPropValue = newVal;
512 mCache.clear();
513 }
514 }
515 })
516#endif
517 {}
518
519 bool checkPermission(uid_t uid, pid_t pid) {
520 std::lock_guard l{mLock};
521 auto it = mCache.find(uid);
522 if (it == mCache.end()) {
523 it = mCache.insert({uid, mPc.checkPermission(BLUETOOTH_PERM, pid, uid)}).first;
524 }
525 return it->second;
526 }
527};
528
529// Don't call this from locks, since it potentially calls up to system server!
530// Check for non-app UIDs above this method!
531bool checkBluetoothPermission(const AttributionSourceState& attr) {
532 [[clang::no_destroy]] static BluetoothPermissionCache impl{};
533 return impl.checkPermission(attr.uid, attr.pid);
534}
535} // anonymous
536
537/**
538 * Determines if the MAC address in Bluetooth device descriptors returned by APIs of
539 * a native audio service (audio flinger, audio policy) must be anonymized.
540 * MAC addresses returned to system server or apps with BLUETOOTH_CONNECT permission
541 * are not anonymized.
542 *
543 * @param attributionSource The attribution source of the calling app.
544 * @param caller string identifying the caller for logging.
545 * @return true if the MAC addresses must be anonymized, false otherwise.
546 */
547bool mustAnonymizeBluetoothAddress(
548 const AttributionSourceState& attributionSource, const String16&) {
549 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
550 bool res;
551 switch(multiuser_get_app_id(uid)) {
552 case AID_ROOT:
553 case AID_SYSTEM:
554 case AID_RADIO:
555 case AID_BLUETOOTH:
556 case AID_MEDIA:
557 case AID_AUDIOSERVER:
558 // Don't anonymize for privileged clients
559 res = false;
560 break;
561 default:
562 res = !checkBluetoothPermission(attributionSource);
563 break;
564 }
565 ALOGV("%s uid: %d, result: %d", __func__, uid, res);
566 return res;
567}
568
569/**
570 * Modifies the passed MAC address string in place for consumption by unprivileged clients.
571 * the string is assumed to have a valid MAC address format.
572 * the anonymization must be kept in sync with toAnonymizedAddress() in BluetoothUtils.java
573 *
574 * @param address input/output the char string contining the MAC address to anonymize.
575 */
576void anonymizeBluetoothAddress(char *address) {
577 if (address == nullptr || strlen(address) != strlen("AA:BB:CC:DD:EE:FF")) {
578 return;
579 }
580 memcpy(address, "XX:XX:XX:XX", strlen("XX:XX:XX:XX"));
581}
582
Oreste Salerno703ec262020-12-17 16:38:38 +0100583sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800584 const sp<IServiceManager> sm = defaultServiceManager();
585 if (sm == nullptr) {
586 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700587 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800588 }
589 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
590 if (packageManager == nullptr) {
591 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700592 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800593 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700594 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800595}
596
597std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
598 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700599 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100600 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700601 if (mPackageManager == nullptr) {
602 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
603 return std::nullopt;
604 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800605 }
606
Oreste Salerno703ec262020-12-17 16:38:38 +0100607 // Retrieve package names for the UID and transform to a std::vector<std::string>.
608 Vector<String16> str16PackageNames;
609 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800610 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100611 for (const auto& str16PackageName : str16PackageNames) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000612 packageNames.emplace_back(String8(str16PackageName).c_str());
Kevin Rocard8be94972019-02-22 13:26:25 -0800613 }
614 if (packageNames.empty()) {
615 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100616 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800617 return std::nullopt;
618 }
619 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100620 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800621 if (!status.isOk()) {
622 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
623 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
624 return std::nullopt;
625 }
626 if (packageNames.size() != isAllowed.size()) {
627 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
628 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
629 return std::nullopt;
630 }
631
632 // Zip together packageNames and isAllowed for debug logs
633 Packages& packages = mDebugLog[uid];
634 packages.resize(packageNames.size()); // Reuse all objects
635 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
636 begin(packages), [] (auto& name, bool isAllowed) -> Package {
637 return {std::move(name), isAllowed};
638 });
639
640 // Only allow playback record if all packages in this UID allow it
641 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
642 [](bool b) { return b; });
643
644 return playbackCaptureAllowed;
645}
646
647void MediaPackageManager::dump(int fd, int spaces) const {
648 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
649 if (mPackageManager == nullptr) {
650 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
651 }
652 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
653
654 for (const auto& uidCache : mDebugLog) {
655 for (const auto& package : std::get<Packages>(uidCache)) {
656 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
657 std::get<const uid_t>(uidCache),
658 package.playbackCaptureAllowed ? "true " : "false",
659 package.name.c_str());
660 }
661 }
662}
663
Andy Hungb26a1c82024-08-30 11:54:40 -0700664namespace mediautils {
665
Andy Hunga85efab2019-12-23 11:41:29 -0800666// How long we hold info before we re-fetch it (24 hours) if we found it previously.
667static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
668// Maximum info records we retain before clearing everything.
669static constexpr size_t INFO_CACHE_MAX = 1000;
670
671// The original code is from MediaMetricsService.cpp.
Andy Hungb26a1c82024-08-30 11:54:40 -0700672std::shared_ptr<const UidInfo::Info> UidInfo::getCachedInfo(uid_t uid)
Andy Hunga85efab2019-12-23 11:41:29 -0800673{
Andy Hungb26a1c82024-08-30 11:54:40 -0700674 std::shared_ptr<const UidInfo::Info> info;
675
Andy Hunga85efab2019-12-23 11:41:29 -0800676 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hunga85efab2019-12-23 11:41:29 -0800677 {
678 std::lock_guard _l(mLock);
679 auto it = mInfoMap.find(uid);
680 if (it != mInfoMap.end()) {
681 info = it->second;
682 ALOGV("%s: uid %d expiration %lld now %lld",
Andy Hungb26a1c82024-08-30 11:54:40 -0700683 __func__, uid, (long long)info->expirationNs, (long long)now);
684 if (info->expirationNs <= now) {
Andy Hunga85efab2019-12-23 11:41:29 -0800685 // purge the stale entry and fall into re-fetching
686 ALOGV("%s: entry for uid %d expired, now %lld",
687 __func__, uid, (long long)now);
688 mInfoMap.erase(it);
Andy Hungb26a1c82024-08-30 11:54:40 -0700689 info.reset(); // force refetch
Andy Hunga85efab2019-12-23 11:41:29 -0800690 }
691 }
692 }
693
694 // if we did not find it in our map, look it up
Andy Hungb26a1c82024-08-30 11:54:40 -0700695 if (!info) {
Andy Hunga85efab2019-12-23 11:41:29 -0800696 sp<IServiceManager> sm = defaultServiceManager();
697 sp<content::pm::IPackageManagerNative> package_mgr;
698 if (sm.get() == nullptr) {
699 ALOGE("%s: Cannot find service manager", __func__);
700 } else {
701 sp<IBinder> binder = sm->getService(String16("package_native"));
702 if (binder.get() == nullptr) {
703 ALOGE("%s: Cannot find package_native", __func__);
704 } else {
705 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
706 }
707 }
708
709 // find package name
710 std::string pkg;
711 if (package_mgr != nullptr) {
712 std::vector<std::string> names;
713 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
714 if (!status.isOk()) {
715 ALOGE("%s: getNamesForUids failed: %s",
716 __func__, status.exceptionMessage().c_str());
717 } else {
718 if (!names[0].empty()) {
719 pkg = names[0].c_str();
720 }
721 }
722 }
723
724 if (pkg.empty()) {
725 struct passwd pw{}, *result;
726 char buf[8192]; // extra buffer space - should exceed what is
727 // required in struct passwd_pw (tested),
728 // and even then this is only used in backup
729 // when the package manager is unavailable.
730 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
731 && result != nullptr
732 && result->pw_name != nullptr) {
733 pkg = result->pw_name;
734 }
735 }
736
737 // strip any leading "shared:" strings that came back
738 if (pkg.compare(0, 7, "shared:") == 0) {
739 pkg.erase(0, 7);
740 }
741
742 // determine how pkg was installed and the versionCode
743 std::string installer;
744 int64_t versionCode = 0;
745 bool notFound = false;
746 if (pkg.empty()) {
747 pkg = std::to_string(uid); // not found
748 notFound = true;
749 } else if (strchr(pkg.c_str(), '.') == nullptr) {
750 // not of form 'com.whatever...'; assume internal
751 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800752 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
753 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800754 } else if (package_mgr.get() != nullptr) {
755 String16 pkgName16(pkg.c_str());
756 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
757 if (!status.isOk()) {
758 ALOGE("%s: getInstallerForPackage failed: %s",
759 __func__, status.exceptionMessage().c_str());
760 }
761
762 // skip if we didn't get an installer
763 if (status.isOk()) {
764 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
765 if (!status.isOk()) {
766 ALOGE("%s: getVersionCodeForPackage failed: %s",
767 __func__, status.exceptionMessage().c_str());
768 }
769 }
770
771 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
772 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
773 }
774
775 // add it to the map, to save a subsequent lookup
776 std::lock_guard _l(mLock);
777 // first clear if we have too many cached elements. This would be rare.
778 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
779
Andy Hungb26a1c82024-08-30 11:54:40 -0700780 info = std::make_shared<const UidInfo::Info>(
781 uid,
782 std::move(pkg),
783 std::move(installer),
784 versionCode,
785 now + (notFound ? 0 : INFO_EXPIRATION_NS));
Andy Hunga85efab2019-12-23 11:41:29 -0800786 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
Andy Hungb26a1c82024-08-30 11:54:40 -0700787 __func__, uid, info->package.c_str(), (long long)info->expirationNs);
Andy Hunga85efab2019-12-23 11:41:29 -0800788 mInfoMap[uid] = info;
789 }
790 return info;
791}
792
Andy Hungb26a1c82024-08-30 11:54:40 -0700793/* static */
794UidInfo& UidInfo::getUidInfo() {
795 [[clang::no_destroy]] static UidInfo uidInfo;
796 return uidInfo;
797}
798
799/* static */
800std::shared_ptr<const UidInfo::Info> UidInfo::getInfo(uid_t uid) {
801 return UidInfo::getUidInfo().getCachedInfo(uid);
802}
803
804} // namespace mediautils
805
Glenn Kasten44deb052012-02-05 18:09:08 -0800806} // namespace android