blob: 2d55f39b2550d47995254056ee77fcb8f6a78406 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 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 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Charles Chenf075f082024-03-04 23:32:55 +000041#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080043#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/MemoryBase.h>
46#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080049#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070050#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070052#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080053#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080054#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070056#include "hidl/HidlCameraService.h"
57#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080058#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070059#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080061#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070063#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000064#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070065#include <utils/Errors.h>
66#include <utils/Log.h>
67#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070068#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080069#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080070#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080071#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080072#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070073#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000074#include <binder/IServiceManager.h>
75#include <binder/IActivityManager.h>
Austin Borgered99f642023-06-01 16:51:35 -070076#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080077
Ruben Brunkb2119af2014-05-09 19:57:56 -070078#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
80#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070081#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070082#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070083#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000084#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070085#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070086#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080089namespace {
90 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080091 const char* kActivityServiceName = "activity";
92 const char* kSensorPrivacyServiceName = "sensor_privacy";
93 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070094 const char* kProcessInfoServiceName = "processinfo";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080095}; // namespace anonymous
96
Mathias Agopian65ab4712010-07-14 17:59:35 -070097namespace android {
98
Austin Borgerea931242021-12-13 23:10:41 +000099using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700100using namespace camera3::SessionConfigurationUtils;
101
102using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700103using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700104using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800105using hardware::ICamera;
106using hardware::ICameraClient;
107using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800108using hardware::camera2::ICameraInjectionCallback;
109using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800110using hardware::camera2::utils::CameraIdAndSessionConfiguration;
111using hardware::camera2::utils::ConcurrentCameraIdCombination;
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700112namespace flags = com::android::internal::camera::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115// Logging support -- this is for debugging only
116// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700117volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118
Steve Blockb8a80522011-12-20 16:23:08 +0000119#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
120#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121
122static void setLogLevel(int level) {
123 android_atomic_write(level, &gLogLevel);
124}
125
Henri Chataingbcb99452023-11-01 17:40:30 +0000126int32_t format_as(CameraService::StatusInternal s) {
127 return fmt::underlying(s);
128}
129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131
Charles Chenf075f082024-03-04 23:32:55 +0000132static const std::string sDumpPermission("android.permission.DUMP");
133static const std::string sManageCameraPermission("android.permission.MANAGE_CAMERA");
134static const std::string sCameraPermission("android.permission.CAMERA");
135static const std::string sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
136static const std::string sCameraHeadlessSystemUserPermission(
137 "android.permission.CAMERA_HEADLESS_SYSTEM_USER");
138static const std::string sCameraPrivacyAllowlistPermission(
139 "android.permission.CAMERA_PRIVACY_ALLOWLIST");
140static const std::string
141 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
142static const std::string sCameraOpenCloseListenerPermission(
143 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
144static const std::string
145 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000146// Constant integer for FGS Logging, used to denote the API type for logger
147static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700148const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800149static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
150static constexpr int32_t kSystemNativeClientState =
151 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700152static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700153
Austin Borgered99f642023-06-01 16:51:35 -0700154const std::string CameraService::kOfflineDevice("offline-");
155const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700156
Rucha Katakward9ea6452021-05-06 11:57:16 -0700157// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700158static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700159
Austin Borger74fca042022-05-23 12:41:21 -0700160CameraService::CameraService(
Charles Chenf075f082024-03-04 23:32:55 +0000161 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
Austin Borger74fca042022-05-23 12:41:21 -0700162 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
163 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800164 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800165 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700166 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700167 mSoundRef(0), mInitialized(false),
168 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000169 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800170 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700171 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
172 if (mMemFd == -1) {
173 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175}
176
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800177// The word 'System' here does not refer to clients only on the system
178// partition. They just need to have a android system uid.
179static bool doesClientHaveSystemUid() {
180 return (CameraThreadState::getCallingUid() < AID_APP_START);
181}
182
Charles Chena7b613c2023-01-24 21:57:33 +0000183// Enable processes with isolated AID to request the binder
184void CameraService::instantiate() {
185 CameraService::publish(true);
186}
187
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800188void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700189 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800190 return;
191 }
192
193 ALOGV("appops service registered. setting camera audio restriction");
194 mAppOps.setCameraAudioRestriction(mAudioRestriction);
195}
196
Iliyan Malchev8951a972011-04-14 16:55:59 -0700197void CameraService::onFirstRef()
198{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700199
Ruben Brunkcc776712015-02-17 20:18:47 -0800200 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800201
Iliyan Malchev8951a972011-04-14 16:55:59 -0700202 BnCameraService::onFirstRef();
203
Ruben Brunk99e69712015-05-26 17:25:07 -0700204 // Update battery life tracking if service is restarting
205 BatteryNotifier& notifier(BatteryNotifier::getInstance());
206 notifier.noteResetCamera();
207 notifier.noteResetFlashlight();
208
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800209 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800210
Emilian Peevf53f66e2017-04-11 14:29:43 +0100211 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800212 if (res == OK) {
213 mInitialized = true;
214 }
215
Svet Ganova453d0d2018-01-11 15:37:58 -0800216 mUidPolicy = new UidPolicy(this);
217 mUidPolicy->registerSelf();
Charles Chenf075f082024-03-04 23:32:55 +0000218 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800219 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800220 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800221
222 // appops function setCamerAudioRestriction uses getService which
223 // is blocking till the appops service is ready. To enable early
224 // boot availability for cameraservice, use checkService which is
225 // non blocking and register for notifications
226 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700227 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800228 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700229 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800230 } else {
231 mAppOps.setCameraAudioRestriction(mAudioRestriction);
232 }
233
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700234 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
235 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000236 // Deprecated, so it will fail to register on newer devices
237 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700238 __FUNCTION__);
239 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700240
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700241 if (!AidlCameraService::registerService(this)) {
242 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
243 }
244
Shuzhen Wang24b44152019-09-20 10:38:11 -0700245 // This needs to be last call in this function, so that it's as close to
246 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700247 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700248 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800249}
250
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800251status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800252 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100253
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800254 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000255 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800256 {
257 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800258
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800259 if (nullptr == mCameraProviderManager.get()) {
260 mCameraProviderManager = new CameraProviderManager();
261 res = mCameraProviderManager->initialize(this);
262 if (res != OK) {
263 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
264 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700265 logServiceError("Unable to initialize camera provider manager",
266 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100268 }
269 }
270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271
272 // Setup vendor tags before we call get_camera_info the first time
273 // because HAL might need to setup static vendor keys in get_camera_info
274 // TODO: maybe put this into CameraProviderManager::initialize()?
275 mCameraProviderManager->setUpVendorTags();
276
277 if (nullptr == mFlashlight.get()) {
278 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700279 }
280
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800281 res = mFlashlight->findFlashUnits();
282 if (res != OK) {
283 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
284 }
285
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000286 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800287 }
288
289
290 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700291 if (getCameraState(cameraId) == nullptr) {
292 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800293 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000294 if (unavailPhysicalIds.count(cameraId) > 0) {
295 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700296 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 }
298 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800299 }
300
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700301 // Derive primary rear/front cameras, and filter their charactierstics.
302 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700303 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700304 // Assume internal cameras are advertised from the same
305 // provider. If multiple providers are registered at different time,
306 // and each provider contains multiple internal color cameras, the current
307 // logic may filter the characteristics of more than one front/rear color
308 // cameras.
309 Mutex::Autolock l(mServiceLock);
310 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700311 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700312
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800313 return OK;
314}
315
Austin Borgered99f642023-06-01 16:51:35 -0700316void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700317 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800318 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800319 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700320 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
321 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000322 ALOGV("%s: Skipping torch callback for system-only camera device %s",
323 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700324 continue;
325 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700326 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700327 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700328 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
329 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000330 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
331 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700332 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000333 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
334 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700335 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000336 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
337 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
338 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800339 }
340}
341
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800343 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800344 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800345 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800346 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347}
348
Emilian Peevaee727d2017-05-04 16:35:48 +0100349void CameraService::onNewProviderRegistered() {
350 enumerateProviders();
351}
352
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700353void CameraService::filterAPI1SystemCameraLocked(
354 const std::vector<std::string> &normalDeviceIds) {
355 mNormalDeviceIdsWithoutSystemCamera.clear();
356 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700358 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700359 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
360 continue;
361 }
362 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700363 // All system camera ids will necessarily come after public camera
364 // device ids as per the HAL interface contract.
365 break;
366 }
367 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
368 }
369 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
370 mNormalDeviceIdsWithoutSystemCamera.size());
371}
372
Austin Borgered99f642023-06-01 16:51:35 -0700373status_t CameraService::getSystemCameraKind(const std::string& cameraId,
374 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700375 auto state = getCameraState(cameraId);
376 if (state != nullptr) {
377 *kind = state->getSystemCameraKind();
378 return OK;
379 }
380 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700381 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382}
383
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800384void CameraService::updateCameraNumAndIds() {
385 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700386 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
387 // Excludes hidden secure cameras
388 mNumberOfCameras =
389 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
390 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800391 mNormalDeviceIds =
392 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800394}
395
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700396void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700397 // To claim to be S Performance primary cameras, the cameras must be
398 // backward compatible. So performance class primary camera Ids must be API1
399 // compatible.
400 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
401 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
402 int facing = -1;
403 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800404 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700405 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800406 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700407 if (facing == -1) {
408 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
409 return;
410 }
411
412 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
413 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700414 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
415 if (res == OK) {
416 mPerfClassPrimaryCameraIds.insert(cameraId);
417 } else {
418 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
419 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
420 break;
421 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422
423 if (facing == hardware::CAMERA_FACING_BACK) {
424 firstRearCameraSeen = true;
425 }
426 if (facing == hardware::CAMERA_FACING_FRONT) {
427 firstFrontCameraSeen = true;
428 }
429 }
430
431 if (firstRearCameraSeen && firstFrontCameraSeen) {
432 break;
433 }
434 }
435}
436
Austin Borgered99f642023-06-01 16:51:35 -0700437void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700438 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100439 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
440 if (res != OK) {
441 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
442 return;
443 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000444 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700445 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
446 if (res != OK) {
447 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
448 return;
449 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000450 std::vector<std::string> physicalCameraIds;
451 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700452 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700454 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100455 }
456
457 {
458 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700459 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000460 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100461 }
462
Austin Borgered99f642023-06-01 16:51:35 -0700463 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100464 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700465 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800466
Austin Borgered99f642023-06-01 16:51:35 -0700467 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100468 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800469
470 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700471 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100472}
473
Austin Borgered99f642023-06-01 16:51:35 -0700474void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800475 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700476 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100477 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700478 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100479 }
480
481 {
482 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700483 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100484 }
485}
486
Austin Borgered99f642023-06-01 16:51:35 -0700487void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800488 CameraDeviceStatus newHalStatus) {
489 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700490 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700491
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800492 StatusInternal newStatus = mapToInternal(newHalStatus);
493
Austin Borgered99f642023-06-01 16:51:35 -0700494 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800495
496 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700497 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700499 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100500
501 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700502 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100503
Austin Borgered99f642023-06-01 16:51:35 -0700504 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700505 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700506 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700507 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700508 return;
509 }
510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800512
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800514 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700515 return;
516 }
517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000519 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
520 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800521
522 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
523 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700524 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800525
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800526 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700527 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800528 // Don't do this in updateStatus to avoid deadlock over mServiceLock
529 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700530
Ruben Brunkcc776712015-02-17 20:18:47 -0800531 // Remove cached shim parameters
532 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700533
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800534 // Remove online as well as offline client from the list of active clients,
535 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700536 clientToDisconnectOnline = removeClientLocked(cameraId);
537 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700538 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800539
Austin Borgered99f642023-06-01 16:51:35 -0700540 disconnectClient(cameraId, clientToDisconnectOnline);
541 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700542
Austin Borgered99f642023-06-01 16:51:35 -0700543 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800544 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000546 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
547 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700548 }
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700550 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800551}
Igor Murashkincba2c162013-03-20 15:56:31 -0700552
Austin Borgered99f642023-06-01 16:51:35 -0700553void CameraService::onDeviceStatusChanged(const std::string& id,
554 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800555 CameraDeviceStatus newHalStatus) {
556 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700557 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800558
559 StatusInternal newStatus = mapToInternal(newHalStatus);
560
561 std::shared_ptr<CameraState> state = getCameraState(id);
562
563 if (state == nullptr) {
564 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700565 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800566 return;
567 }
568
569 StatusInternal logicalCameraStatus = state->getStatus();
570 if (logicalCameraStatus != StatusInternal::PRESENT &&
571 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
572 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700573 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800574 return;
575 }
576
577 bool updated = false;
578 if (newStatus == StatusInternal::PRESENT) {
579 updated = state->removeUnavailablePhysicalId(physicalId);
580 } else {
581 updated = state->addUnavailablePhysicalId(physicalId);
582 }
583
584 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700585 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800586 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000587 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800588 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000589 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800590 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700591 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
592 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
593 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700594 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700595 return;
596 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 Mutex::Autolock lock(mStatusListenerLock);
598 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700599 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
600 listener->getListenerPid(), listener->getListenerUid())) {
601 ALOGV("Skipping discovery callback for system-only camera device %s",
602 id.c_str());
603 continue;
604 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700605 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700606 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700607 listener->handleBinderStatus(ret,
608 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
609 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
610 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800611 }
612 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700613}
614
Austin Borgered99f642023-06-01 16:51:35 -0700615void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800616 if (clientToDisconnect.get() != nullptr) {
617 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700618 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800619 // Notify the client of disconnection
620 clientToDisconnect->notifyError(
621 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
622 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800623 clientToDisconnect->disconnect();
624 }
625}
626
Austin Borgered99f642023-06-01 16:51:35 -0700627void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800628 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700629 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
630 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
631 if (res != OK) {
632 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700633 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700634 return;
635 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800636 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700637 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800638}
639
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700642 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
643 Mutex::Autolock al(mTorchStatusMutex);
644 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
645}
646
Austin Borgered99f642023-06-01 16:51:35 -0700647void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800648 int32_t newStrengthLevel) {
649 Mutex::Autolock lock(mStatusListenerLock);
650 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700651 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700652 i->handleBinderStatus(ret,
653 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
654 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800655 }
656}
657
Austin Borgered99f642023-06-01 16:51:35 -0700658void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700659 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800660 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700661 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800663 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800664 status_t res = getTorchStatusLocked(cameraId, &status);
665 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700666 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700667 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800668 return;
669 }
670 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800671 return;
672 }
673
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800674 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800675 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800676 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
677 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678 return;
679 }
680
Ruben Brunkcc776712015-02-17 20:18:47 -0800681 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700682 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700683 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700684 auto iter = mTorchUidMap.find(cameraId);
685 if (iter != mTorchUidMap.end()) {
686 int oldUid = iter->second.second;
687 int newUid = iter->second.first;
688 BatteryNotifier& notifier(BatteryNotifier::getInstance());
689 if (oldUid != newUid) {
690 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800691 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700692 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700693 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800694 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700695 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700696 }
697 iter->second.second = newUid;
698 } else {
699 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800700 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700701 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700702 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700703 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700704 }
705 }
706 }
707 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700708 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709}
710
Charles Chenf075f082024-03-04 23:32:55 +0000711static bool isAutomotiveDevice() {
712 // Checks the property ro.hardware.type and returns true if it is
713 // automotive.
714 char value[PROPERTY_VALUE_MAX] = {0};
715 property_get("ro.hardware.type", value, "");
716 return strncmp(value, "automotive", PROPERTY_VALUE_MAX) == 0;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700717}
718
Charles Chenf075f082024-03-04 23:32:55 +0000719static bool isHeadlessSystemUserMode() {
720 // Checks if the device is running in headless system user mode
721 // by checking the property ro.fw.mu.headless_system_user.
722 char value[PROPERTY_VALUE_MAX] = {0};
723 property_get("ro.fw.mu.headless_system_user", value, "");
724 return strncmp(value, "true", PROPERTY_VALUE_MAX) == 0;
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700725}
726
Charles Chenf075f082024-03-04 23:32:55 +0000727static bool isAutomotivePrivilegedClient(int32_t uid) {
728 // Returns false if this is not an automotive device type.
729 if (!isAutomotiveDevice())
730 return false;
731
732 // Returns true if the uid is AID_AUTOMOTIVE_EVS which is a
733 // privileged client uid used for safety critical use cases such as
734 // rear view and surround view.
735 return uid == AID_AUTOMOTIVE_EVS;
736}
737
738bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const{
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700739 // Returns false if this is not an automotive device type.
740 if (!isAutomotiveDevice())
741 return false;
742
743 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700744 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700745 return false;
746
747 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
748 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
749 // This isn't a known camera ID, so it's not a system camera.
750 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
751 return false;
752 }
753
754 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
755 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
756 return false;
757 }
758
759 CameraMetadata cameraInfo;
760 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700761 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700762 if (res != OK){
763 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
764 cam_id.c_str());
765 return false;
766 }
767
768 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
769 if (auto_location.count != 1)
770 return false;
771
772 uint8_t location = auto_location.data.u8[0];
773 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
774 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
775 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
776 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
777 return false;
778 }
779
780 return true;
781}
782
Charles Chenf075f082024-03-04 23:32:55 +0000783bool CameraService::checkPermission(const std::string& cameraId, const std::string& permission,
784 const AttributionSourceState& attributionSource, const std::string& message,
785 int32_t attributedOpCode) const{
786 if (isAutomotivePrivilegedClient(attributionSource.uid)) {
787 // If cameraId is empty, then it means that this check is not used for the
788 // purpose of accessing a specific camera, hence grant permission just
789 // based on uid to the automotive privileged client.
790 if (cameraId.empty())
791 return true;
792 // If this call is used for accessing a specific camera then cam_id must be provided.
793 // In that case, only pre-grants the permission for accessing the exterior system only
794 // camera.
795 return isAutomotiveExteriorSystemCamera(cameraId);
796 }
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700797
Charles Chenf075f082024-03-04 23:32:55 +0000798 permission::PermissionChecker permissionChecker;
799 return permissionChecker.checkPermissionForPreflight(toString16(permission), attributionSource,
800 toString16(message), attributedOpCode)
801 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700802}
803
Austin Borger1c1bee02023-06-01 16:51:35 -0700804bool CameraService::hasPermissionsForSystemCamera(const std::string& cameraId, int callingPid,
Charles Chenf075f082024-03-04 23:32:55 +0000805 int callingUid) const{
806 AttributionSourceState attributionSource{};
807 attributionSource.pid = callingPid;
808 attributionSource.uid = callingUid;
809 bool checkPermissionForSystemCamera = checkPermission(cameraId,
810 sSystemCameraPermission, attributionSource, std::string(), AppOpsManager::OP_NONE);
811 bool checkPermissionForCamera = checkPermission(cameraId,
812 sCameraPermission, attributionSource, std::string(), AppOpsManager::OP_NONE);
813 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700814}
815
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700816bool CameraService::hasPermissionsForCameraHeadlessSystemUser(const std::string& cameraId,
Charles Chenf075f082024-03-04 23:32:55 +0000817 int callingPid, int callingUid) const{
818 AttributionSourceState attributionSource{};
819 attributionSource.pid = callingPid;
820 attributionSource.uid = callingUid;
821 return checkPermission(cameraId, sCameraHeadlessSystemUserPermission, attributionSource,
822 std::string(), AppOpsManager::OP_NONE);
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700823}
824
Charles Chenf075f082024-03-04 23:32:55 +0000825bool CameraService::hasPermissionsForCameraPrivacyAllowlist(int callingPid, int callingUid) const{
826 AttributionSourceState attributionSource{};
827 attributionSource.pid = callingPid;
828 attributionSource.uid = callingUid;
829 return checkPermission(std::string(), sCameraPrivacyAllowlistPermission, attributionSource,
830 std::string(), AppOpsManager::OP_NONE);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +0000831}
832
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700834 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100835 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700836 bool hasSystemCameraPermissions =
Austin Borger1c1bee02023-06-01 16:51:35 -0700837 hasPermissionsForSystemCamera(std::string(), CameraThreadState::getCallingPid(),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700838 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700839 switch (type) {
840 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700841 if (hasSystemCameraPermissions) {
842 *numCameras = static_cast<int>(mNormalDeviceIds.size());
843 } else {
844 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
845 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800846 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700847 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700848 if (hasSystemCameraPermissions) {
849 *numCameras = mNumberOfCameras;
850 } else {
851 *numCameras = mNumberOfCamerasWithoutSystemCamera;
852 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800853 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700854 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800855 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700856 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800857 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
858 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700859 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800860 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861}
862
malikakash73125c62023-07-21 22:44:34 +0000863Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700864 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000865 const int pid = CameraThreadState::getCallingPid();
866 const int uid = CameraThreadState::getCallingUid();
867 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
868 __FUNCTION__, pid, uid);
869 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
870 "Permission Denial: no permission to configure camera id mapping");
871 }
872 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000873 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000874 if (!parseStatus.isOk()) {
875 return parseStatus;
876 }
877 remapCameraIds(cameraIdRemappingMap);
878 return Status::ok();
879}
880
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700881Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
882 /* out */
883 hardware::camera2::impl::CameraMetadataNative* request) {
884 ATRACE_CALL();
885
886 if (!flags::feature_combination_query()) {
887 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
888 "Camera subsystem doesn't support this method!");
889 }
890 if (!mInitialized) {
891 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
892 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
893 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
894 }
895
896 const std::string cameraId = resolveCameraId(unresolvedCameraId,
897 CameraThreadState::getCallingUid());
898
899 binder::Status res;
900 if (request == nullptr) {
901 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
902 "Camera %s: Error creating default request", cameraId.c_str());
903 return res;
904 }
905 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
906 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
907 cameraId, templateId, &tempId);
908 if (!res.isOk()) {
909 ALOGE("%s: Camera %s: failed to map request Template %d",
910 __FUNCTION__, cameraId.c_str(), templateId);
911 return res;
912 }
913
914 if (shouldRejectSystemCameraConnection(cameraId)) {
915 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
916 "request for system only device %s: ", cameraId.c_str());
917 }
918
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700919 CameraMetadata metadata;
920 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
921 if (err == OK) {
922 request->swap(metadata);
923 } else if (err == BAD_VALUE) {
924 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
925 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
926 cameraId.c_str(), templateId, strerror(-err), err);
927 } else {
928 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
929 "Camera %s: Error creating default request for template %d: %s (%d)",
930 cameraId.c_str(), templateId, strerror(-err), err);
931 }
932 return res;
933}
934
935Status CameraService::isSessionConfigurationWithParametersSupported(
936 const std::string& unresolvedCameraId,
937 const SessionConfiguration& sessionConfiguration,
938 /*out*/
939 bool* supported) {
940 ATRACE_CALL();
941
942 if (!flags::feature_combination_query()) {
943 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
944 "Camera subsystem doesn't support this method!");
945 }
946 if (!mInitialized) {
947 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
948 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
949 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
950 }
951
952 const std::string cameraId = resolveCameraId(unresolvedCameraId,
953 CameraThreadState::getCallingUid());
954 if (supported == nullptr) {
955 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
956 unresolvedCameraId.c_str());
957 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
958 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
959 }
960
961 if (shouldRejectSystemCameraConnection(cameraId)) {
962 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
963 "session configuration with parameters support for system only device %s: ",
964 cameraId.c_str());
965 }
966
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700967 *supported = false;
968 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
969 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
970 supported);
971 binder::Status res;
972 switch (ret) {
973 case OK:
974 // Expected, do nothing.
975 break;
976 case INVALID_OPERATION: {
977 std::string msg = fmt::sprintf(
978 "Camera %s: Session configuration query not supported!",
979 cameraId.c_str());
980 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
981 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
982 }
983
984 break;
985 default: {
986 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
987 strerror(-ret), ret);
988 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
989 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
990 msg.c_str());
991 }
992 }
993
994 return res;
995}
996
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800997Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
998 int targetSdkVersion, bool overrideToPortrait,
999 const SessionConfiguration& sessionConfiguration,
1000 /*out*/ CameraMetadata* outMetadata) {
1001 ATRACE_CALL();
1002
1003 if (!mInitialized) {
1004 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1005 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1006 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1007 }
1008
1009 const std::string cameraId =
1010 resolveCameraId(unresolvedCameraId, CameraThreadState::getCallingUid());
1011
1012 if (outMetadata == nullptr) {
1013 std::string msg =
1014 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1015 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1016 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1017 }
1018
1019 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1020 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
1021
1022 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1023 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1024
1025 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
1026 // camera access permission.
1027
1028 Status res = Status::ok();
1029 switch (ret) {
1030 case OK:
1031 // Expected, no handling needed.
1032 break;
1033 case INVALID_OPERATION: {
1034 std::string msg = fmt::sprintf(
1035 "Camera %s: Session characteristics query not supported!",
1036 cameraId.c_str());
1037 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
1038 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1039 }
1040 break;
1041 default: {
1042 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
1043 strerror(-ret), ret);
1044 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1045 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1046 }
1047 }
1048
1049 return res;
1050}
1051
malikakash82ed4352023-07-21 22:44:34 +00001052Status CameraService::parseCameraIdRemapping(
1053 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001054 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001055 std::string packageName;
1056 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +00001057 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001058 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001059 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001060 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1061 "CameraIdRemapping: Package name cannot be empty");
1062 }
malikakash214f6e62023-08-10 23:50:56 +00001063 if (packageIdRemapping.cameraIdsToReplace.size()
1064 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001065 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1066 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001067 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001068 }
malikakash214f6e62023-08-10 23:50:56 +00001069 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001070 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1071 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001072 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001073 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1074 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001075 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001076 }
1077 if (cameraIdToReplace == updatedCameraId) {
1078 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1079 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1080 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001081 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001082 }
1083 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001084 }
1085 }
1086 return Status::ok();
1087}
1088
1089void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1090 // Acquire mServiceLock and prevent other clients from connecting
1091 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1092 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1093
malikakashedb38962023-09-06 00:03:35 +00001094 // Collect all existing clients for camera Ids that are being
1095 // remapped in the new cameraIdRemapping, but only if they were being used by a
1096 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001097 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001098 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001099 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1100 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001101 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001102 id0.c_str(), id1.c_str());
1103 auto clientDescriptor = mActiveClientManager.get(id0);
1104 if (clientDescriptor != nullptr) {
1105 sp<BasicClient> clientSp = clientDescriptor->getValue();
1106 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001107 // This camera is being used by a targeted packageName and
1108 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001109 clientsToDisconnect.push_back(clientSp);
1110 cameraIdsToUpdate.push_back(id0);
1111 }
1112 }
1113 }
1114 }
1115
malikakashedb38962023-09-06 00:03:35 +00001116 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001117 // Notify the clients about the disconnection.
1118 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001119 CaptureResultExtras{});
1120 }
malikakash82ed4352023-07-21 22:44:34 +00001121
1122 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1123 // blocking other clients from connecting in mServiceLockWrapper if held.
1124 mServiceLock.unlock();
1125
malikakashedb38962023-09-06 00:03:35 +00001126 // Clear calling identity for disconnect() PID checks.
1127 int64_t token = CameraThreadState::clearCallingIdentity();
1128
malikakash82ed4352023-07-21 22:44:34 +00001129 // Disconnect clients.
1130 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001131 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1132 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001133 clientSp->disconnect();
1134 }
1135
malikakashedb38962023-09-06 00:03:35 +00001136 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1137 clientsToDisconnect.clear();
1138
1139 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001140 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001141
1142 {
1143 Mutex::Autolock lock(mCameraIdRemappingLock);
1144 // Update mCameraIdRemapping.
1145 mCameraIdRemapping.clear();
1146 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1147 }
malikakash82ed4352023-07-21 22:44:34 +00001148}
1149
malikakash22af94c2023-12-04 18:13:14 +00001150Status CameraService::injectSessionParams(
1151 const std::string& cameraId,
1152 const CameraMetadata& sessionParams) {
1153 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1154 const int pid = CameraThreadState::getCallingPid();
1155 const int uid = CameraThreadState::getCallingUid();
1156 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1157 __FUNCTION__, pid, uid);
1158 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1159 "Permission Denial: no permission to inject session params");
1160 }
1161
1162 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1163 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1164
1165 auto clientDescriptor = mActiveClientManager.get(cameraId);
1166 if (clientDescriptor == nullptr) {
1167 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1168 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1169 "No active client for camera id %s", cameraId.c_str());
1170 }
1171
1172 sp<BasicClient> clientSp = clientDescriptor->getValue();
1173 status_t res = clientSp->injectSessionParams(sessionParams);
1174
1175 if (res != OK) {
1176 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1177 "Error injecting session params into camera \"%s\": %s (%d)",
1178 cameraId.c_str(), strerror(-res), res);
1179 }
1180 return Status::ok();
1181}
1182
Austin Borgered99f642023-06-01 16:51:35 -07001183std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1184 const std::string& inputCameraId, int clientUid) {
1185 std::string packageName = getPackageNameFromUid(clientUid);
1186 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001187 Mutex::Autolock lock(mCameraIdRemappingLock);
1188 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1189 packageMapIter != mCameraIdRemapping.end()) {
1190 for (auto& [id0, id1]: packageMapIter->second) {
1191 if (id1 == inputCameraId) {
1192 cameraIds.push_back(id0);
1193 }
1194 }
1195 }
1196 return cameraIds;
1197}
1198
Austin Borgered99f642023-06-01 16:51:35 -07001199std::string CameraService::resolveCameraId(
1200 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001201 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001202 const std::string& packageName) {
1203 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001204 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001205 packageNameVal = getPackageNameFromUid(clientUid);
1206 }
malikakash65d20692023-09-07 01:06:33 +00001207 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001208 // We shouldn't remap cameras for processes with system/vendor UIDs.
1209 return inputCameraId;
1210 }
malikakash82ed4352023-07-21 22:44:34 +00001211 Mutex::Autolock lock(mCameraIdRemappingLock);
1212 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1213 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001214 auto packageMap = packageMapIter->second;
1215 if (auto replacementIdIter = packageMap.find(inputCameraId);
1216 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001217 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001218 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001219 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001220 replacementIdIter->second.c_str());
1221 return replacementIdIter->second;
1222 }
1223 }
1224 return inputCameraId;
1225}
1226
Austin Borger18b30a72022-10-27 12:20:29 -07001227Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001228 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001229 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001230 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001231 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1232 std::string cameraIdStr = resolveCameraId(
1233 unresolvedCameraId, CameraThreadState::getCallingUid());
1234
Austin Borgered99f642023-06-01 16:51:35 -07001235 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001236 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1237 "characteristics for system only device %s: ", cameraIdStr.c_str());
1238 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001239
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001240 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001241 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return STATUS_ERROR(ERROR_DISCONNECTED,
1243 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001244 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001245 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001246 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001247 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1248 if (hasSystemCameraPermissions) {
1249 cameraIdBound = mNumberOfCameras;
1250 }
1251 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001252 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1253 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 }
1255
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001256 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001257 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001258 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001259 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001260 if (err != OK) {
1261 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1262 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1263 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001264 logServiceError(std::string("Error retrieving camera info from device ")
1265 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001266 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001267
Ruben Brunkcc776712015-02-17 20:18:47 -08001268 return ret;
1269}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001271std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001272 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
1273 auto callingPid = CameraThreadState::getCallingPid();
1274 auto callingUid = CameraThreadState::getCallingUid();
Charles Chenf075f082024-03-04 23:32:55 +00001275 AttributionSourceState attributionSource{};
1276 attributionSource.pid = callingPid;
1277 attributionSource.uid = callingUid;
1278 bool checkPermissionForSystemCamera = checkPermission(std::to_string(cameraIdInt),
1279 sSystemCameraPermission, attributionSource, std::string(),
1280 AppOpsManager::OP_NONE);
1281 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001282 deviceIds = &mNormalDeviceIds;
1283 }
1284 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001285 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001286 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001287 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001288 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001289
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001290 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001291}
1292
Austin Borgered99f642023-06-01 16:51:35 -07001293std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001294 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001295 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001296}
1297
Austin Borgered99f642023-06-01 16:51:35 -07001298Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001299 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001300 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001301
malikakashedb38962023-09-06 00:03:35 +00001302 const std::string cameraId = resolveCameraId(unresolvedCameraId,
1303 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001304
Zhijun He2b59be82013-09-25 10:14:30 -07001305 if (!cameraInfo) {
1306 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001307 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001308 }
1309
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001310 if (!mInitialized) {
1311 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001312 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001313 return STATUS_ERROR(ERROR_DISCONNECTED,
1314 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001315 }
1316
Austin Borgered99f642023-06-01 16:51:35 -07001317 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001318 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001319 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001320 }
1321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001322 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001323
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001324 bool overrideForPerfClass =
1325 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001326 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001327 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001328 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001329 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001330 if (res == NAME_NOT_FOUND) {
1331 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001332 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001333 strerror(-res), res);
1334 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001335 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1336 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001337 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001338 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001339 strerror(-res), res);
1340 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001341 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001342 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001343 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1344 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001345 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001346 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001347 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001348 int callingPid = CameraThreadState::getCallingPid();
1349 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001350 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001351 // If it's not calling from cameraserver, check the permission only if
1352 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1353 // it would've already been checked in shouldRejectSystemCameraConnection.
Charles Chenf075f082024-03-04 23:32:55 +00001354 AttributionSourceState attributionSource{};
1355 attributionSource.pid = callingPid;
1356 attributionSource.uid = callingUid;
1357 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission,
1358 attributionSource, std::string(), AppOpsManager::OP_NONE);
Emilian Peeve20c6372018-08-14 18:45:53 +01001359 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001360 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001361 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001362 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001363 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001364 &tagsRemoved);
1365 if (res != OK) {
1366 cameraInfo->clear();
1367 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1368 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001369 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001370 }
1371 }
1372
1373 if (!tagsRemoved.empty()) {
1374 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1375 tagsRemoved.data(), tagsRemoved.size());
1376 if (res != OK) {
1377 cameraInfo->clear();
1378 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001379 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001380 strerror(-res), res);
1381 }
1382 }
1383
Zhijun He2b59be82013-09-25 10:14:30 -07001384 return ret;
1385}
1386
malikakashedb38962023-09-06 00:03:35 +00001387Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001388 int32_t* torchStrength) {
1389 ATRACE_CALL();
1390 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001391 const std::string cameraId = resolveCameraId(
malikakash65d20692023-09-07 01:06:33 +00001392 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001393 if (!mInitialized) {
1394 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1395 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1396 }
1397
1398 if(torchStrength == NULL) {
1399 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1400 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1401 }
1402
Austin Borgered99f642023-06-01 16:51:35 -07001403 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001404 if (res != OK) {
1405 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001406 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001407 strerror(-res), res);
1408 }
1409 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1410 return Status::ok();
1411}
1412
Austin Borgered99f642023-06-01 16:51:35 -07001413std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001414 time_t now = time(nullptr);
1415 char formattedTime[64];
1416 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001417 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001418}
1419
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001420Status CameraService::getCameraVendorTagDescriptor(
1421 /*out*/
1422 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001423 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001424 if (!mInitialized) {
1425 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001426 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001427 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001428 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1429 if (globalDescriptor != nullptr) {
1430 *desc = *(globalDescriptor.get());
1431 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001432 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001433}
1434
Emilian Peev71c73a22017-03-21 16:35:51 +00001435Status CameraService::getCameraVendorTagCache(
1436 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1437 ATRACE_CALL();
1438 if (!mInitialized) {
1439 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1440 return STATUS_ERROR(ERROR_DISCONNECTED,
1441 "Camera subsystem not available");
1442 }
1443 sp<VendorTagDescriptorCache> globalCache =
1444 VendorTagDescriptorCache::getGlobalVendorTagCache();
1445 if (globalCache != nullptr) {
1446 *cache = *(globalCache.get());
1447 }
1448 return Status::ok();
1449}
1450
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001451void CameraService::clearCachedVariables() {
1452 BasicClient::BasicClient::sCameraService = nullptr;
1453}
1454
Austin Borgered99f642023-06-01 16:51:35 -07001455std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001456 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001457 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001458
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001459 int deviceVersion = 0;
1460
Emilian Peevf53f66e2017-04-11 14:29:43 +01001461 status_t res;
1462 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001463 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001464 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001465 if (res != OK || transport == IPCTransport::INVALID) {
1466 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001467 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001468 return std::make_pair(-1, IPCTransport::INVALID) ;
1469 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001470 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001471
Emilian Peevf53f66e2017-04-11 14:29:43 +01001472 hardware::CameraInfo info;
1473 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001474 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001475 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001476 if (res != OK) {
1477 return std::make_pair(-1, IPCTransport::INVALID);
1478 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001479 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001480 if (orientation) {
1481 *orientation = info.orientation;
1482 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001483 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001484
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001486}
1487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001488Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001489 switch(err) {
1490 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001491 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001492 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001493 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1494 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001495 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 return STATUS_ERROR(ERROR_DISCONNECTED,
1497 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001498 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001499 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1500 "Camera HAL encountered error %d: %s",
1501 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001502 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001503}
1504
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001505Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001506 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1507 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001508 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001509 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001510 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001511 bool forceSlowJpegMode, const std::string& originalCameraId,
1512 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001513 // For HIDL devices
1514 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1515 // Create CameraClient based on device version reported by the HAL.
1516 int deviceVersion = deviceVersionAndTransport.first;
1517 switch(deviceVersion) {
1518 case CAMERA_DEVICE_API_VERSION_1_0:
1519 ALOGE("Camera using old HAL version: %d", deviceVersion);
1520 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1521 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001522 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001523 break;
1524 case CAMERA_DEVICE_API_VERSION_3_0:
1525 case CAMERA_DEVICE_API_VERSION_3_1:
1526 case CAMERA_DEVICE_API_VERSION_3_2:
1527 case CAMERA_DEVICE_API_VERSION_3_3:
1528 case CAMERA_DEVICE_API_VERSION_3_4:
1529 case CAMERA_DEVICE_API_VERSION_3_5:
1530 case CAMERA_DEVICE_API_VERSION_3_6:
1531 case CAMERA_DEVICE_API_VERSION_3_7:
1532 break;
1533 default:
1534 // Should not be reachable
1535 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1536 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1537 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001538 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001539 }
1540 }
1541 if (effectiveApiLevel == API_1) { // Camera1 API route
1542 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001543 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Charles Chenf075f082024-03-04 23:32:55 +00001544 packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001545 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001546 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1547 forceSlowJpegMode);
1548 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1549 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001550 } else { // Camera2 API route
1551 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1552 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001553 *client = new CameraDeviceClient(cameraService, tmp,
Charles Chenf075f082024-03-04 23:32:55 +00001554 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001555 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001556 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001557 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001558 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001559 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001560}
1561
Austin Borgered99f642023-06-01 16:51:35 -07001562std::string CameraService::toString(std::set<userid_t> intSet) {
1563 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001564 bool first = true;
1565 for (userid_t i : intSet) {
1566 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001567 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001568 first = false;
1569 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001570 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001571 }
1572 }
Austin Borgered99f642023-06-01 16:51:35 -07001573 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001574}
1575
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001576int32_t CameraService::mapToInterface(TorchModeStatus status) {
1577 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1578 switch (status) {
1579 case TorchModeStatus::NOT_AVAILABLE:
1580 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1581 break;
1582 case TorchModeStatus::AVAILABLE_OFF:
1583 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1584 break;
1585 case TorchModeStatus::AVAILABLE_ON:
1586 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1587 break;
1588 default:
1589 ALOGW("Unknown new flash status: %d", status);
1590 }
1591 return serviceStatus;
1592}
1593
1594CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1595 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1596 switch (status) {
1597 case CameraDeviceStatus::NOT_PRESENT:
1598 serviceStatus = StatusInternal::NOT_PRESENT;
1599 break;
1600 case CameraDeviceStatus::PRESENT:
1601 serviceStatus = StatusInternal::PRESENT;
1602 break;
1603 case CameraDeviceStatus::ENUMERATING:
1604 serviceStatus = StatusInternal::ENUMERATING;
1605 break;
1606 default:
1607 ALOGW("Unknown new HAL device status: %d", status);
1608 }
1609 return serviceStatus;
1610}
1611
1612int32_t CameraService::mapToInterface(StatusInternal status) {
1613 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1614 switch (status) {
1615 case StatusInternal::NOT_PRESENT:
1616 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1617 break;
1618 case StatusInternal::PRESENT:
1619 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1620 break;
1621 case StatusInternal::ENUMERATING:
1622 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1623 break;
1624 case StatusInternal::NOT_AVAILABLE:
1625 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1626 break;
1627 case StatusInternal::UNKNOWN:
1628 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1629 break;
1630 default:
1631 ALOGW("Unknown new internal device status: %d", status);
1632 }
1633 return serviceStatus;
1634}
1635
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001636Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001637 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001638
Austin Borgered99f642023-06-01 16:51:35 -07001639 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001641 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001642 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001643 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1644 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001645 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001646 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001647 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001649 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001650 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001651 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001652}
1653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001655 /*out*/
1656 CameraParameters* parameters) {
1657
1658 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001660 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001661
1662 if (parameters == NULL) {
1663 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001664 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001665 }
1666
malikakashedb38962023-09-06 00:03:35 +00001667 std::string unresolvedCameraId = std::to_string(cameraId);
1668 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1669 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001670
1671 // Check if we already have parameters
1672 {
1673 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001674 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001675 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001676 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001677 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001678 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001679 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001680 }
1681 CameraParameters p = cameraState->getShimParams();
1682 if (!p.isEmpty()) {
1683 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001684 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001685 }
1686 }
1687
Jayant Chowdhary12361932018-08-27 14:46:13 -07001688 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001689 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001690 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001691 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001692 // Error already logged by callee
1693 return ret;
1694 }
1695
1696 // Check for parameters again
1697 {
1698 // Scope for service lock
1699 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001700 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001701 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001702 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001703 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001704 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001705 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 CameraParameters p = cameraState->getShimParams();
1707 if (!p.isEmpty()) {
1708 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001709 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001710 }
1711 }
1712
Ruben Brunkcc776712015-02-17 20:18:47 -08001713 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1714 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001715 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001716}
1717
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001718// Can camera service trust the caller based on the calling UID?
Charles Chenf075f082024-03-04 23:32:55 +00001719static bool isTrustedCallingUid(uid_t uid) {
1720 switch (uid) {
1721 case AID_MEDIA: // mediaserver
1722 case AID_CAMERASERVER: // cameraserver
1723 case AID_RADIO: // telephony
1724 return true;
1725 default:
1726 return false;
1727 }
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001728}
1729
Charles Chenf075f082024-03-04 23:32:55 +00001730static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1731 int err) {
1732 PermissionController pc;
1733 uid = pc.getPackageUid(toString16(packageName), 0);
1734 if (uid <= 0) {
1735 ALOGE("Unknown package: '%s'", packageName.c_str());
1736 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
1737 return BAD_VALUE;
1738 }
1739
1740 if (userId < 0) {
1741 ALOGE("Invalid user: %d", userId);
1742 dprintf(err, "Invalid user: %d\n", userId);
1743 return BAD_VALUE;
1744 }
1745
1746 uid = multiuser_get_uid(userId, uid);
1747 return NO_ERROR;
Nicholas Sauera3620332019-04-03 14:05:17 -07001748}
1749
Austin Borgered99f642023-06-01 16:51:35 -07001750Status CameraService::validateConnectLocked(const std::string& cameraId,
1751 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001752 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001753
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001754#ifdef __BRILLO__
1755 UNUSED(clientName8);
1756 UNUSED(clientUid);
1757 UNUSED(clientPid);
1758 UNUSED(originalClientPid);
1759#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001760 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1761 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001762 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001763 return allowed;
1764 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001765#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001766
Jayant Chowdhary12361932018-08-27 14:46:13 -07001767 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001768
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001769 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001770 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1771 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001772 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001773 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001774 }
1775
Ruben Brunkcc776712015-02-17 20:18:47 -08001776 if (getCameraState(cameraId) == nullptr) {
1777 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001778 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001779 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001780 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 }
1782
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001783 status_t err = checkIfDeviceIsUsable(cameraId);
1784 if (err != NO_ERROR) {
1785 switch(err) {
1786 case -ENODEV:
1787 case -EBUSY:
1788 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001789 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001790 default:
1791 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001792 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001793 }
1794 }
1795 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001796}
1797
Austin Borgered99f642023-06-01 16:51:35 -07001798Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1799 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001800 /*out*/int& originalClientPid) const {
Charles Chenf075f082024-03-04 23:32:55 +00001801 AttributionSourceState attributionSource{};
1802
Jayant Chowdhary12361932018-08-27 14:46:13 -07001803 int callingPid = CameraThreadState::getCallingPid();
1804 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001806 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001808 clientUid = callingUid;
1809 } else if (!isTrustedCallingUid(callingUid)) {
1810 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1811 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001812 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1813 "Untrusted caller (calling PID %d, UID %d) trying to "
1814 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001815 callingPid, callingUid, cameraId.c_str(),
1816 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817 }
1818
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001819 // Check if we can trust clientPid
1820 if (clientPid == USE_CALLING_PID) {
1821 clientPid = callingPid;
1822 } else if (!isTrustedCallingUid(callingUid)) {
1823 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1824 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001825 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1826 "Untrusted caller (calling PID %d, UID %d) trying to "
1827 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001828 callingPid, callingUid, cameraId.c_str(),
1829 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001830 }
1831
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001832 if (shouldRejectSystemCameraConnection(cameraId)) {
1833 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1834 cameraId.c_str());
1835 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001836 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001837 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001838 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1839 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001840 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001841 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001842 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001843
1844 }
1845
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001846 // If it's not calling from cameraserver, check the permission if the
1847 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1848 // android.permission.SYSTEM_CAMERA for system only camera devices).
Charles Chenf075f082024-03-04 23:32:55 +00001849 attributionSource.pid = clientPid;
1850 attributionSource.uid = clientUid;
1851 attributionSource.packageName = clientName;
1852 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission, attributionSource,
1853 std::string(), AppOpsManager::OP_NONE);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001854 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001855 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001856 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001857 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1858 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001859 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001860 }
1861
Svet Ganova453d0d2018-01-11 15:37:58 -08001862 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001863 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001864 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001865 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1866 clientPid, clientUid);
1867 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001868 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1869 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001870 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001871 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001872 }
1873
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001874 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1875 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1876 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1877 if ((!isAutomotivePrivilegedClient(callingUid) ||
1878 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1879 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001880 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1881 return STATUS_ERROR_FMT(ERROR_DISABLED,
1882 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001883 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001884 }
1885
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001886 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1887 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001888 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001889 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
Ruben Brunk6267b532015-04-30 17:44:07 -07001891 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001892
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001893 // For non-system clients : Only allow clients who are being used by the current foreground
1894 // device user, unless calling from our own process.
1895 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001896 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001897 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1898 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001899 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001900 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1901 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001902 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001903 }
1904
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001905 if (flags::camera_hsum_permission()) {
1906 // If the System User tries to access the camera when the device is running in
1907 // headless system user mode, ensure that client has the required permission
1908 // CAMERA_HEADLESS_SYSTEM_USER.
Charles Chenf075f082024-03-04 23:32:55 +00001909 if (isHeadlessSystemUserMode() && (clientUserId == USER_SYSTEM) &&
1910 !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001911 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1912 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1913 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1914 User without camera headless system user permission",
1915 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
1916 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001917 }
1918
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001919 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001920}
1921
Austin Borgered99f642023-06-01 16:51:35 -07001922status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001923 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001924 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001925 if (cameraState == nullptr) {
1926 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001927 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001928 return -ENODEV;
1929 }
1930
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001931 StatusInternal currentStatus = cameraState->getStatus();
1932 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001933 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001934 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001935 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001936 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001937 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001938 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001939 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001940 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001941
Ruben Brunkcc776712015-02-17 20:18:47 -08001942 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001943}
1944
Ruben Brunkcc776712015-02-17 20:18:47 -08001945void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001946 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001947
Ruben Brunkcc776712015-02-17 20:18:47 -08001948 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001949 auto clientDescriptor =
1950 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001951 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001952 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1953
1954 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001955 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001956
1957 if (evicted.size() > 0) {
1958 // This should never happen - clients should already have been removed in disconnect
1959 for (auto& i : evicted) {
1960 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001961 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001962 }
1963
1964 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1965 __FUNCTION__);
1966 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001967
1968 // And register a death notification for the client callback. Do
1969 // this last to avoid Binder policy where a nested Binder
1970 // transaction might be pre-empted to service the client death
1971 // notification if the client process dies before linkToDeath is
1972 // invoked.
1973 sp<IBinder> remoteCallback = client->getRemote();
1974 if (remoteCallback != nullptr) {
1975 remoteCallback->linkToDeath(this);
1976 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001977}
1978
Austin Borgered99f642023-06-01 16:51:35 -07001979status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1980 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1981 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001982 /*out*/
1983 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001984 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001985 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001986 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001987 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001988 DescriptorPtr clientDescriptor;
1989 {
1990 if (effectiveApiLevel == API_1) {
1991 // If we are using API1, any existing client for this camera ID with the same remote
1992 // should be returned rather than evicted to allow MediaRecorder to work properly.
1993
1994 auto current = mActiveClientManager.get(cameraId);
1995 if (current != nullptr) {
1996 auto clientSp = current->getValue();
1997 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001998 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001999 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002000 " API level, evicting prior client...");
2001 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002002 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002003 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002004 *client = clientSp;
2005 return NO_ERROR;
2006 }
2007 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002008 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002009 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002010
Ruben Brunkcc776712015-02-17 20:18:47 -08002011 // Get state for the given cameraId
2012 auto state = getCameraState(cameraId);
2013 if (state == nullptr) {
2014 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002015 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002016 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002017 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002018 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002019
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002020 sp<IServiceManager> sm = defaultServiceManager();
2021 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
2022 if (!binder && isAutomotivePrivilegedClient(CameraThreadState::getCallingUid())) {
2023 // If processinfo service is not available and the client is automotive privileged
2024 // client used for safety critical uses cases such as rear-view and surround-view which
2025 // needs to be available before android boot completes, then use the hardcoded values
2026 // for the process state and priority score. As this scenario is before android system
2027 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2028 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2029 // visible on the top.
2030 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2031 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2032 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2033 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2034 } else {
2035 // Get current active client PIDs
2036 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2037 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002038
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002039 std::vector<int> priorityScores(ownerPids.size());
2040 std::vector<int> states(ownerPids.size());
2041
2042 // Get priority scores of all active PIDs
2043 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2044 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2045 if (err != OK) {
2046 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2047 return err;
2048 }
2049
2050 // Update all active clients' priorities
2051 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2052 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2053 pidToPriorityMap.emplace(ownerPids[i],
2054 resource_policy::ClientPriority(priorityScores[i], states[i],
2055 /* isVendorClient won't get copied over*/ false,
2056 /* oomScoreOffset won't get copied over*/ 0));
2057 }
2058 mActiveClientManager.updatePriorities(pidToPriorityMap);
2059
2060 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2061 int32_t actualState = states[states.size() - 1];
2062
2063 // Make descriptor for incoming client. We store the oomScoreOffset
2064 // since we might need it later on new handleEvictionsLocked and
2065 // ProcessInfoService would not take that into account.
2066 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2067 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2068 state->getConflicting(), actualScore, clientPid, actualState,
2069 oomScoreOffset, systemNativeClient);
2070 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002071
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002072 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2073
Ruben Brunkcc776712015-02-17 20:18:47 -08002074 // Find clients that would be evicted
2075 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2076
2077 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2078 // background, so we cannot do evictions
2079 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2080 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2081 " priority).", clientPid);
2082
2083 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002084 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002085 auto incompatibleClients =
2086 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2087
Austin Borgered99f642023-06-01 16:51:35 -07002088 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2089 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2090 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002091 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002092
2093 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002094 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002095 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002096 i->getKey().c_str(),
2097 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002098 i->getOwnerId(), i->getPriority().getScore(),
2099 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002100 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002101 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2102 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002103 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002104 }
2105
2106 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002107 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002108 mEventLog.add(msg);
2109
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002110 auto current = mActiveClientManager.get(cameraId);
2111 if (current != nullptr) {
2112 return -EBUSY; // CAMERA_IN_USE
2113 } else {
2114 return -EUSERS; // MAX_CAMERAS_IN_USE
2115 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002116 }
2117
2118 for (auto& i : evicted) {
2119 sp<BasicClient> clientSp = i->getValue();
2120 if (clientSp.get() == nullptr) {
2121 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2122
2123 // TODO: Remove this
2124 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2125 __FUNCTION__);
2126 mActiveClientManager.remove(i);
2127 continue;
2128 }
2129
2130 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002131 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002132 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002133
Ruben Brunkcc776712015-02-17 20:18:47 -08002134 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002135 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002136 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2137 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002138 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002139 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002140 i->getPriority().getState(), cameraId.c_str(),
2141 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002142 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002143
2144 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002145 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002146 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002147 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002148 }
2149
Ruben Brunkcc776712015-02-17 20:18:47 -08002150 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2151 // other clients from connecting in mServiceLockWrapper if held
2152 mServiceLock.unlock();
2153
2154 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002155 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002156
2157 // Destroy evicted clients
2158 for (auto& i : evictedClients) {
2159 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002160 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002161 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002162
Jayant Chowdhary12361932018-08-27 14:46:13 -07002163 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002164
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002165 for (const auto& i : evictedClients) {
2166 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002167 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002168 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2169 if (ret == TIMED_OUT) {
2170 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002171 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2172 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002173 return -EBUSY;
2174 }
2175 if (ret != NO_ERROR) {
2176 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002177 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2178 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002179 return ret;
2180 }
2181 }
2182
2183 evictedClients.clear();
2184
Ruben Brunkcc776712015-02-17 20:18:47 -08002185 // Once clients have been disconnected, relock
2186 mServiceLock.lock();
2187
2188 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2189 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2190 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002191 }
2192
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 *partial = clientDescriptor;
2194 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002195}
2196
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002197Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002198 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002199 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002200 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002201 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002202 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002203 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002204 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002205 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002206 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002207 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002208
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002209 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002210 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002211
malikakashedb38962023-09-06 00:03:35 +00002212 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2213 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
2214 CameraThreadState::getCallingUid());
2215
Ruben Brunkcc776712015-02-17 20:18:47 -08002216 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002217 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2218 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002219 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002220 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002221
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002222 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002223 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
2224 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002226 }
2227
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002228 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002229
2230 const sp<IServiceManager> sm(defaultServiceManager());
2231 const auto& mActivityManager = getActivityManager();
2232 if (mActivityManager) {
2233 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2234 CameraThreadState::getCallingUid(),
2235 CameraThreadState::getCallingPid());
2236 }
2237
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002238 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002239}
2240
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002241bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2242 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002243 // If the client is not a vendor client, don't add listener if
2244 // a) the camera is a publicly hidden secure camera OR
2245 // b) the camera is a system only camera and the client doesn't
2246 // have android.permission.SYSTEM_CAMERA permissions.
2247 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2248 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002249 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002250 return true;
2251 }
2252 return false;
2253}
2254
Austin Borgered99f642023-06-01 16:51:35 -07002255bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002256 // Rules for rejection:
2257 // 1) If cameraserver tries to access this camera device, accept the
2258 // connection.
2259 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002260 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002261 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2262 // and the serving thread is a non hwbinder thread, the client must have
2263 // android.permission.SYSTEM_CAMERA permissions to connect.
2264
2265 int cPid = CameraThreadState::getCallingPid();
2266 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002267 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002268 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2269 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002270 // This isn't a known camera ID, so it's not a system camera
2271 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2272 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002273 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002274
2275 // (1) Cameraserver trying to connect, accept.
Charles Chenf075f082024-03-04 23:32:55 +00002276 if (CameraThreadState::getCallingPid() == getpid()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002277 return false;
2278 }
2279 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002280 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002281 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2282 return true;
2283 }
2284 // (3) Here we only check for permissions if it is a system only camera device. This is since
2285 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2286 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2287 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002288 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002289 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002290 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2291 cameraId.c_str());
2292 return true;
2293 }
2294
2295 return false;
2296}
2297
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298Status CameraService::connectDevice(
2299 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002300 const std::string& unresolvedCameraId,
2301 const std::string& clientPackageName,
2302 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002303 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002304 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002305 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002307
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002308 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002309 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002310 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002311 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002312 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002313 bool systemNativeClient = false;
2314 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
2315 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07002316 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
2317 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002318 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002319 }
malikakashedb38962023-09-06 00:03:35 +00002320 const std::string cameraId = resolveCameraId(
2321 unresolvedCameraId,
2322 CameraThreadState::getCallingUid(),
2323 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002324
2325 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002326 std::string msg =
2327 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2328 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2329 cameraId.c_str());
2330 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2331 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002332 }
2333
Austin Borger9bfa0a72022-08-03 17:50:40 -07002334 userid_t clientUserId = multiuser_get_user_id(clientUid);
2335 int callingUid = CameraThreadState::getCallingUid();
2336 if (clientUid == USE_CALLING_UID) {
2337 clientUserId = multiuser_get_user_id(callingUid);
2338 }
2339
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002340 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2341 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002342 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2343 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002344 std::string msg = "Camera disabled by device policy";
2345 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2346 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002347 }
2348
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002349 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002350 if (oomScoreOffset > 0
2351 && !hasPermissionsForSystemCamera(cameraId, callingPid,
2352 CameraThreadState::getCallingUid())
2353 && !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07002354 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002355 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002356 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2357 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2358 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002359 }
2360
Austin Borgered99f642023-06-01 16:51:35 -07002361 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2362 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002363 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002364 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002365 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002366
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002367 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002368 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002369 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002370 }
2371
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002372 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002373 Mutex::Autolock lock(mServiceLock);
2374
2375 // Clear the previous cached logs and reposition the
2376 // file offset to beginning of the file to log new data.
2377 // If either truncate or lseek fails, close the previous file and create a new one.
2378 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2379 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2380 // Close the previous memfd.
2381 close(mMemFd);
2382 // If failure to wipe the data, then create a new file and
2383 // assign the new value to mMemFd.
2384 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2385 if (mMemFd == -1) {
2386 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2387 }
2388 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002389 const sp<IServiceManager> sm(defaultServiceManager());
2390 const auto& mActivityManager = getActivityManager();
2391 if (mActivityManager) {
2392 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2393 CameraThreadState::getCallingUid(),
2394 CameraThreadState::getCallingPid());
2395 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002396 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002397}
2398
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002399bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2400 int callingPid, int callingUid) {
2401 if (!isAutomotiveDevice()) {
2402 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2403 }
2404
2405 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2406 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2407 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2408 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2409 "using camera %s", callingUid, cam_id.c_str());
2410 return false;
2411 }
2412
2413 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2414 return true;
2415 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2416 return false;
2417 } else if ((mSensorPrivacyPolicy->getCameraPrivacyState()
2418 == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS) ||
2419 (mSensorPrivacyPolicy->getCameraPrivacyState()
2420 == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS) ||
2421 (mSensorPrivacyPolicy->getCameraPrivacyState() ==
2422 SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_APPS)) {
2423 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2424 return false;
2425 } else {
2426 return true;
2427 }
2428 }
2429 return false;
2430}
2431
Austin Borgered99f642023-06-01 16:51:35 -07002432std::string CameraService::getPackageNameFromUid(int clientUid) {
2433 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002434
2435 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002436 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002437 if (binder == 0) {
2438 ALOGE("Cannot get permission service");
2439 // Return empty package name and the further interaction
2440 // with camera will likely fail
2441 return packageName;
2442 }
2443
2444 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2445 Vector<String16> packages;
2446
2447 permCtrl->getPackagesForUid(clientUid, packages);
2448
2449 if (packages.isEmpty()) {
2450 ALOGE("No packages for calling UID %d", clientUid);
2451 // Return empty package name and the further interaction
2452 // with camera will likely fail
2453 return packageName;
2454 }
2455
2456 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002457 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002458
2459 return packageName;
2460}
2461
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002462template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002463Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2464 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2465 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002466 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002467 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002468 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002469 binder::Status ret = binder::Status::ok();
2470
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002471 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002472 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002473 int packageUid = (clientUid == USE_CALLING_UID) ?
2474 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002475 if (clientPackageNameMaybe.size() <= 0) {
2476 // NDK calls don't come with package names, but we need one for various cases.
2477 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2478 // do exist. For all authentication cases, all packages under the same UID get the
2479 // same permissions, so picking any associated package name is sufficient. For some
2480 // other cases, this may give inaccurate names for clients in logs.
2481 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002482 clientPackageName = getPackageNameFromUid(packageUid);
2483 } else {
2484 clientPackageName = clientPackageNameMaybe;
2485 }
2486
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002487 int originalClientPid = 0;
2488
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002489 int packagePid = (clientPid == USE_CALLING_PID) ?
2490 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002491 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002492 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002493 static_cast<int>(effectiveApiLevel));
2494
Shuzhen Wang316781a2020-08-18 18:11:01 -07002495 nsecs_t openTimeNs = systemTime();
2496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002498 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002499 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002500
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002501 {
2502 // Acquire mServiceLock and prevent other clients from connecting
2503 std::unique_ptr<AutoConditionLock> lock =
2504 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2505
2506 if (lock == nullptr) {
2507 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2508 , clientPid);
2509 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2510 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002511 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002512 }
2513
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002514 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002515 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002516 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2517 return ret;
2518 }
2519
2520 // Check the shim parameters after acquiring lock, if they have already been updated and
2521 // we were doing a shim update, return immediately
2522 if (shimUpdateOnly) {
2523 auto cameraState = getCameraState(cameraId);
2524 if (cameraState != nullptr) {
2525 if (!cameraState->getShimParams().isEmpty()) return ret;
2526 }
2527 }
2528
2529 status_t err;
2530
2531 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002532 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002533 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002534 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2535 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002536 switch (err) {
2537 case -ENODEV:
2538 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2539 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002540 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002541 case -EBUSY:
2542 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2543 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002544 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002545 case -EUSERS:
2546 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2547 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002548 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002549 default:
2550 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2551 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002552 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002553 }
2554 }
2555
2556 if (clientTmp.get() != nullptr) {
2557 // Handle special case for API1 MediaRecorder where the existing client is returned
2558 device = static_cast<CLIENT*>(clientTmp.get());
2559 return ret;
2560 }
2561
2562 // give flashlight a chance to close devices if necessary.
2563 mFlashlight->prepareDeviceOpen(cameraId);
2564
Austin Borger18b30a72022-10-27 12:20:29 -07002565 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002566 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002567 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2568 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002569 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002570 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002571 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002572 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002573 }
2574
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002575 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002576 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002577 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002578 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002579 clientFeatureId, cameraId, api1CameraId, facing,
2580 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002581 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002582 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002583 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002584 return ret;
2585 }
2586 client = static_cast<CLIENT*>(tmp.get());
2587
2588 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2589 __FUNCTION__);
2590
Austin Borgered99f642023-06-01 16:51:35 -07002591 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002592 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002593 if (err != OK) {
2594 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002595 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002596 mServiceLock.unlock();
2597 client->disconnect();
2598 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002599 switch(err) {
2600 case BAD_VALUE:
2601 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002602 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002603 case -EBUSY:
2604 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002605 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002606 case -EUSERS:
2607 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2608 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002609 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002610 case PERMISSION_DENIED:
2611 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002612 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002613 case -EACCES:
2614 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002615 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002616 case -ENODEV:
2617 default:
2618 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002619 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002620 strerror(-err), err);
2621 }
2622 }
2623
2624 // Update shim paremeters for legacy clients
2625 if (effectiveApiLevel == API_1) {
2626 // Assume we have always received a Client subclass for API1
2627 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2628 String8 rawParams = shimClient->getParameters();
2629 CameraParameters params(rawParams);
2630
2631 auto cameraState = getCameraState(cameraId);
2632 if (cameraState != nullptr) {
2633 cameraState->setShimParams(params);
2634 } else {
2635 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002636 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002637 }
2638 }
2639
Ravneetaeb20dc2022-03-30 05:33:03 +00002640 // Enable/disable camera service watchdog
2641 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2642
Emilian Peev6d45db82024-01-18 20:11:54 +00002643 CameraMetadata chars;
2644 bool rotateAndCropSupported = true;
2645 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2646 &chars, overrideToPortrait);
2647 if (err == OK) {
2648 auto availableRotateCropEntry = chars.find(
2649 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2650 if (availableRotateCropEntry.count <= 1) {
2651 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002652 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002653 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002654 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2655 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002656 }
2657
Emilian Peev6d45db82024-01-18 20:11:54 +00002658 if (rotateAndCropSupported) {
2659 // Set rotate-and-crop override behavior
2660 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2661 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2662 } else if (overrideToPortrait && portraitRotation != 0) {
2663 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2664 switch (portraitRotation) {
2665 case 90:
2666 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2667 break;
2668 case 180:
2669 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2670 break;
2671 case 270:
2672 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2673 break;
2674 default:
2675 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2676 break;
2677 }
2678 client->setRotateAndCropOverride(rotateAndCropMode);
2679 } else {
2680 client->setRotateAndCropOverride(
2681 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2682 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2683 }
2684 }
2685
2686 bool autoframingSupported = true;
2687 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2688 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2689 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2690 autoframingSupported = false;
2691 }
2692
2693 if (autoframingSupported) {
2694 // Set autoframing override behaviour
2695 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2696 client->setAutoframingOverride(mOverrideAutoframingMode);
2697 } else {
2698 client->setAutoframingOverride(
2699 mCameraServiceProxyWrapper->getAutoframingOverride(
2700 clientPackageName));
2701 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002702 }
2703
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002704 bool isCameraPrivacyEnabled;
2705 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002706 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002707 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2708 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2709 } else {
2710 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002711 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002712 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002713
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002714 if (client->supportsCameraMute()) {
2715 client->setCameraMute(
2716 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2717 } else if (isCameraPrivacyEnabled) {
2718 // no camera mute supported, but privacy is on! => disconnect
2719 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2720 client->getPackageName().c_str(), cameraId.c_str());
2721 // Do not hold mServiceLock while disconnecting clients, but
2722 // retain the condition blocking other clients from connecting
2723 // in mServiceLockWrapper if held.
2724 mServiceLock.unlock();
2725 // Clear caller identity temporarily so client disconnect PID
2726 // checks work correctly
2727 int64_t token = CameraThreadState::clearCallingIdentity();
2728 // Note AppOp to trigger the "Unblock" dialog
2729 client->noteAppOp();
2730 client->disconnect();
2731 CameraThreadState::restoreCallingIdentity(token);
2732 // Reacquire mServiceLock
2733 mServiceLock.lock();
2734
2735 return STATUS_ERROR_FMT(ERROR_DISABLED,
2736 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002737 }
2738
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002739 if (shimUpdateOnly) {
2740 // If only updating legacy shim parameters, immediately disconnect client
2741 mServiceLock.unlock();
2742 client->disconnect();
2743 mServiceLock.lock();
2744 } else {
2745 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002746 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002747 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002748
2749 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002750 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002751 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002752 } // lock is destroyed, allow further connect calls
2753
2754 // Important: release the mutex here so the client can call back into the service from its
2755 // destructor (can be at the end of the call)
2756 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002757
2758 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002759 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002760 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002761
Cliff Wud3a05312021-04-26 23:07:31 +08002762 {
2763 Mutex::Autolock lock(mInjectionParametersLock);
2764 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2765 mInjectionInitPending = false;
2766 status_t res = NO_ERROR;
2767 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2768 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002769 sp<BasicClient> clientSp = clientDescriptor->getValue();
2770 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2771 if(res != OK) {
2772 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2773 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002774 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002775 }
2776 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002777 if (res != OK) {
2778 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2779 }
2780 } else {
2781 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002782 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002783 res = NO_INIT;
2784 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2785 }
2786 }
2787 }
2788
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002789 return ret;
2790}
2791
Austin Borgered99f642023-06-01 16:51:35 -07002792status_t CameraService::addOfflineClient(const std::string &cameraId,
2793 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002794 if (offlineClient.get() == nullptr) {
2795 return BAD_VALUE;
2796 }
2797
2798 {
2799 // Acquire mServiceLock and prevent other clients from connecting
2800 std::unique_ptr<AutoConditionLock> lock =
2801 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2802
2803 if (lock == nullptr) {
2804 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2805 , __FUNCTION__, offlineClient->getClientPid());
2806 return TIMED_OUT;
2807 }
2808
2809 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2810 if (onlineClientDesc.get() == nullptr) {
2811 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2812 cameraId.c_str());
2813 return BAD_VALUE;
2814 }
2815
2816 // Offline clients do not evict or conflict with other online devices. Resource sharing
2817 // conflicts are handled by the camera provider which will either succeed or fail before
2818 // reaching this method.
2819 const auto& onlinePriority = onlineClientDesc->getPriority();
2820 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2821 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002822 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002823 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002824 // native clients don't have offline processing support.
2825 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002826 if (offlineClientDesc == nullptr) {
2827 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2828 return BAD_VALUE;
2829 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002830
2831 // Allow only one offline device per camera
2832 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2833 if (!incompatibleClients.empty()) {
2834 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2835 return BAD_VALUE;
2836 }
2837
Austin Borgered99f642023-06-01 16:51:35 -07002838 std::string monitorTags = isClientWatched(offlineClient.get())
2839 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002840 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002841 if (err != OK) {
2842 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2843 return err;
2844 }
2845
2846 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2847 if (evicted.size() > 0) {
2848 for (auto& i : evicted) {
2849 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002850 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002851 }
2852
2853 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2854 "properly", __FUNCTION__);
2855
2856 return BAD_VALUE;
2857 }
2858
2859 logConnectedOffline(offlineClientDesc->getKey(),
2860 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002861 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002862
2863 sp<IBinder> remoteCallback = offlineClient->getRemote();
2864 if (remoteCallback != nullptr) {
2865 remoteCallback->linkToDeath(this);
2866 }
2867 } // lock is destroyed, allow further connect calls
2868
2869 return OK;
2870}
2871
Austin Borgered99f642023-06-01 16:51:35 -07002872Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002873 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002874 Mutex::Autolock lock(mServiceLock);
2875
2876 ATRACE_CALL();
2877 if (clientBinder == nullptr) {
2878 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2879 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2880 "Torch client binder in null.");
2881 }
2882
Rucha Katakwar38284522021-11-10 11:25:21 -08002883 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002884 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002885 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002887 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002888 }
2889
2890 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002891 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002892 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002893 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002894 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002895 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002896 }
2897
2898 StatusInternal cameraStatus = state->getStatus();
2899 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2900 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002901 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002902 (int)cameraStatus);
2903 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002904 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002905 }
2906
2907 {
2908 Mutex::Autolock al(mTorchStatusMutex);
2909 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002910 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002911 if (err != OK) {
2912 if (err == NAME_NOT_FOUND) {
2913 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002914 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002915 }
2916 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002917 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2919 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002920 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 }
2922
2923 if (status == TorchModeStatus::NOT_AVAILABLE) {
2924 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2925 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002926 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2928 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002929 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002930 } else {
2931 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002932 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2934 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002935 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002936 }
2937 }
2938 }
2939
2940 {
2941 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002942 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002943 }
2944 // Check if the current torch strength level is same as the new one.
2945 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002946 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002947
Austin Borgered99f642023-06-01 16:51:35 -07002948 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002949
2950 if (err != OK) {
2951 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002952 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002953 switch (err) {
2954 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002955 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2956 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002957 errorCode = ERROR_ILLEGAL_ARGUMENT;
2958 break;
2959 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002960 msg = fmt::sprintf("Camera \"%s\" is in use",
2961 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002962 errorCode = ERROR_CAMERA_IN_USE;
2963 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002964 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002965 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002966 "valid range.", torchStrength);
2967 errorCode = ERROR_ILLEGAL_ARGUMENT;
2968 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002969 default:
Austin Borgered99f642023-06-01 16:51:35 -07002970 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002971 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002972 }
Austin Borgered99f642023-06-01 16:51:35 -07002973 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2974 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002975 }
2976
2977 {
2978 // update the link to client's death
2979 // Store the last client that turns on each camera's torch mode.
2980 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002981 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002982 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002983 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002984 } else {
2985 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2986 mTorchClientMap.replaceValueAt(index, clientBinder);
2987 }
2988 clientBinder->linkToDeath(this);
2989 }
2990
2991 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002992 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002993 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002994 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002995 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002996 }
2997 return Status::ok();
2998}
2999
malikakash73125c62023-07-21 22:44:34 +00003000Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003001 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003002 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003003
3004 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003005 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003006 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003007 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3008 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003009 }
3010
Jayant Chowdhary12361932018-08-27 14:46:13 -07003011 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00003012 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003013
Austin Borgered99f642023-06-01 16:51:35 -07003014 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003015 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003016 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003017 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003018 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003019 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003020 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003021 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003022 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003023 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003024 }
3025
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003026 StatusInternal cameraStatus = state->getStatus();
3027 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003028 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003029 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3030 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003031 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003032 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003033 }
3034
3035 {
3036 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003037 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003038 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003039 if (err != OK) {
3040 if (err == NAME_NOT_FOUND) {
3041 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003042 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003043 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003044 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003045 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003046 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003047 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003048 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003049 }
3050
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003051 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003052 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003053 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003054 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003055 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3056 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003057 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003058 } else {
3059 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003060 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003061 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3062 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003063 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003064 }
3065 }
3066 }
3067
Ruben Brunk99e69712015-05-26 17:25:07 -07003068 {
3069 // Update UID map - this is used in the torch status changed callbacks, so must be done
3070 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003071 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003072 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003073 }
3074
Austin Borgered99f642023-06-01 16:51:35 -07003075 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003076
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003077 if (err != OK) {
3078 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003079 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 switch (err) {
3081 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003082 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3083 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003084 errorCode = ERROR_ILLEGAL_ARGUMENT;
3085 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003086 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003087 msg = fmt::sprintf("Camera \"%s\" is in use",
3088 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003089 errorCode = ERROR_CAMERA_IN_USE;
3090 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003091 default:
Austin Borgered99f642023-06-01 16:51:35 -07003092 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003093 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003094 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003095 errorCode = ERROR_INVALID_OPERATION;
3096 }
Austin Borgered99f642023-06-01 16:51:35 -07003097 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3098 logServiceError(msg, errorCode);
3099 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003100 }
3101
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003102 {
3103 // update the link to client's death
3104 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003105 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003106 if (enabled) {
3107 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003108 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003109 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003110 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003111 mTorchClientMap.replaceValueAt(index, clientBinder);
3112 }
3113 clientBinder->linkToDeath(this);
3114 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003115 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003116 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003117 }
3118
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003119 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003120 std::string torchState = enabled ? "on" : "off";
3121 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3122 torchState.c_str(), clientPid);
3123 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003124 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003125}
3126
Austin Borgered99f642023-06-01 16:51:35 -07003127void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3128 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3129 mTorchUidMap[cameraId].first = uid;
3130 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003131 } else {
3132 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003133 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003134 }
3135}
3136
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003137Status CameraService::notifySystemEvent(int32_t eventId,
3138 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003139 const int pid = CameraThreadState::getCallingPid();
3140 const int selfPid = getpid();
3141
3142 // Permission checks
3143 if (pid != selfPid) {
3144 // Ensure we're being called by system_server, or similar process with
3145 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003146 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003147 const int uid = CameraThreadState::getCallingUid();
3148 ALOGE("Permission Denial: cannot send updates to camera service about system"
3149 " events from pid=%d, uid=%d", pid, uid);
3150 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003151 "No permission to send updates to camera service about system events"
3152 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003153 }
3154 }
3155
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003156 ATRACE_CALL();
3157
Ruben Brunk36597b22015-03-20 22:15:57 -07003158 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003159 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003160 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003161 // from a system server crash
3162 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003163 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003164 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003165 break;
3166 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003167 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3168 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003169 if (args.size() != 1) {
3170 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3171 "USB Device Event requires 1 argument");
3172 }
3173
Valentin Iftime29e2e152021-08-13 15:17:33 +02003174 // Notify CameraProviderManager for lazy HALs
3175 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3176 std::to_string(args[0]));
3177 break;
3178 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003179 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003180 default: {
3181 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3182 eventId);
3183 break;
3184 }
3185 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003186 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003187}
3188
Emilian Peev53722fa2019-02-22 17:47:20 -08003189void CameraService::notifyMonitoredUids() {
3190 Mutex::Autolock lock(mStatusListenerLock);
3191
3192 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003193 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003194 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3195 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003196 }
3197}
3198
Austin Borgerdddb7552023-03-30 17:53:01 -07003199void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3200 Mutex::Autolock lock(mStatusListenerLock);
3201
3202 for (const auto& it : mListenerList) {
3203 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3204 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3205 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3206 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3207 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3208 }
3209 }
3210}
3211
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003212Status CameraService::notifyDeviceStateChange(int64_t newState) {
3213 const int pid = CameraThreadState::getCallingPid();
3214 const int selfPid = getpid();
3215
3216 // Permission checks
3217 if (pid != selfPid) {
3218 // Ensure we're being called by system_server, or similar process with
3219 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003220 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003221 const int uid = CameraThreadState::getCallingUid();
3222 ALOGE("Permission Denial: cannot send updates to camera service about device"
3223 " state changes from pid=%d, uid=%d", pid, uid);
3224 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3225 "No permission to send updates to camera service about device state"
3226 " changes from pid=%d, uid=%d", pid, uid);
3227 }
3228 }
3229
3230 ATRACE_CALL();
3231
Austin Borger18b30a72022-10-27 12:20:29 -07003232 {
3233 Mutex::Autolock lock(mServiceLock);
3234 mDeviceState = newState;
3235 }
3236
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003237 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003238
3239 return Status::ok();
3240}
3241
Emilian Peev8b64f282021-03-25 16:49:57 -07003242Status CameraService::notifyDisplayConfigurationChange() {
3243 ATRACE_CALL();
3244 const int callingPid = CameraThreadState::getCallingPid();
3245 const int selfPid = getpid();
3246
3247 // Permission checks
3248 if (callingPid != selfPid) {
3249 // Ensure we're being called by system_server, or similar process with
3250 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003251 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07003252 const int uid = CameraThreadState::getCallingUid();
3253 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3254 " changes from pid=%d, uid=%d", callingPid, uid);
3255 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3256 "No permission to send updates to camera service about orientation"
3257 " changes from pid=%d, uid=%d", callingPid, uid);
3258 }
3259 }
3260
3261 Mutex::Autolock lock(mServiceLock);
3262
3263 // Don't do anything if rotate-and-crop override via cmd is active
3264 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3265
3266 const auto clients = mActiveClientManager.getAll();
3267 for (auto& current : clients) {
3268 if (current != nullptr) {
3269 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003270 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3271 basicClient->setRotateAndCropOverride(
3272 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3273 basicClient->getPackageName(),
3274 basicClient->getCameraFacing(),
3275 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003276 }
3277 }
3278 }
3279
3280 return Status::ok();
3281}
3282
3283Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003284 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3285 ATRACE_CALL();
3286 if (!concurrentCameraIds) {
3287 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3288 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3289 }
3290
3291 if (!mInitialized) {
3292 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003293 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003294 return STATUS_ERROR(ERROR_DISCONNECTED,
3295 "Camera subsystem is not available");
3296 }
3297 // First call into the provider and get the set of concurrent camera
3298 // combinations
3299 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003300 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003301 for (auto &combination : concurrentCameraCombinations) {
3302 std::vector<std::string> validCombination;
3303 for (auto &cameraId : combination) {
3304 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003305 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003306 if (state == nullptr) {
3307 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3308 continue;
3309 }
3310 StatusInternal status = state->getStatus();
3311 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3312 continue;
3313 }
Austin Borgered99f642023-06-01 16:51:35 -07003314 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003315 continue;
3316 }
3317 validCombination.push_back(cameraId);
3318 }
3319 if (validCombination.size() != 0) {
3320 concurrentCameraIds->push_back(std::move(validCombination));
3321 }
3322 }
3323 return Status::ok();
3324}
3325
Charles Chenf075f082024-03-04 23:32:55 +00003326bool CameraService::hasCameraPermissions() const {
3327 int callingPid = CameraThreadState::getCallingPid();
3328 int callingUid = CameraThreadState::getCallingUid();
3329 AttributionSourceState attributionSource{};
3330 attributionSource.pid = callingPid;
3331 attributionSource.uid = callingUid;
3332 bool res = checkPermission(std::string(), sCameraPermission,
3333 attributionSource, std::string(), AppOpsManager::OP_NONE);
3334
3335 bool hasPermission = ((callingPid == getpid()) || res);
3336 if (!hasPermission) {
3337 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
3338 }
3339 return hasPermission;
3340}
3341
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003342Status CameraService::isConcurrentSessionConfigurationSupported(
3343 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003344 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003345 if (!isSupported) {
3346 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3347 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3348 }
3349
3350 if (!mInitialized) {
3351 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3352 return STATUS_ERROR(ERROR_DISCONNECTED,
3353 "Camera subsystem is not available");
3354 }
3355
3356 // Check for camera permissions
Charles Chenf075f082024-03-04 23:32:55 +00003357 if (!hasCameraPermissions()) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003358 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3359 "android.permission.CAMERA needed to call"
3360 "isConcurrentSessionConfigurationSupported");
3361 }
3362
3363 status_t res =
3364 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003365 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3366 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003367 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003368 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003369 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003370 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3371 "support %s (%d)", strerror(-res), res);
3372 }
3373 return Status::ok();
3374}
3375
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003376Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3377 /*out*/
3378 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003379 return addListenerHelper(listener, cameraStatuses);
3380}
3381
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003382binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3383 std::vector<hardware::CameraStatus>* cameraStatuses) {
3384 return addListenerHelper(listener, cameraStatuses, false, true);
3385}
3386
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003387Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3388 /*out*/
3389 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003390 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003391
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003392 ATRACE_CALL();
3393
Igor Murashkinbfc99152013-02-27 12:55:20 -08003394 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003395
Ruben Brunk3450ba72015-06-16 11:00:37 -07003396 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003397 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003398 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003399 }
3400
Austin Borger17e3ebe2024-02-14 15:02:11 -08003401 auto clientUid = CameraThreadState::getCallingUid();
Charles Chenf075f082024-03-04 23:32:55 +00003402 auto clientPid = CameraThreadState::getCallingPid();
3403 AttributionSourceState attributionSource{};
3404 attributionSource.uid = clientUid;
3405 attributionSource.pid = clientPid;
3406
3407 bool openCloseCallbackAllowed = checkPermission(std::string(),
3408 sCameraOpenCloseListenerPermission, attributionSource, std::string(),
3409 AppOpsManager::OP_NONE);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003410
Igor Murashkinbfc99152013-02-27 12:55:20 -08003411 Mutex::Autolock lock(mServiceLock);
3412
Ruben Brunkcc776712015-02-17 20:18:47 -08003413 {
3414 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003415 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003416 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003417 ALOGW("%s: Tried to add listener %p which was already subscribed",
3418 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003419 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003420 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003421 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003422
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003423 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003424 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3425 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003426 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003427 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003428 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003429 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003430 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3431 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3432 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003433 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003434 // The listener still needs to be added to the list of listeners, regardless of what
3435 // permissions the listener process has / whether it is a vendor listener. Since it might be
3436 // eligible to listen to other camera ids.
3437 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003438 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003439 }
3440
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003441 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003442 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003443 Mutex::Autolock lock(mCameraStatesLock);
3444 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003445 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003446 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003447 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003448 }
3449 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003450 // Remove the camera statuses that should be hidden from the client, we do
3451 // this after collecting the states in order to avoid holding
3452 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3453 // the same time.
3454 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3455 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3456 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3457 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3458 ALOGE("%s: Invalid camera id %s, skipping status update",
3459 __FUNCTION__, s.cameraId.c_str());
3460 return true;
3461 }
3462 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3463 clientUid);}), cameraStatuses->end());
3464
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003465 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003466 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003467 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003468 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003469 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003470
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003471 /*
3472 * Immediately signal current torch status to this listener only
3473 * This may be a subset of all the devices, so don't include it in the response directly
3474 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003475 {
3476 Mutex::Autolock al(mTorchStatusMutex);
3477 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003478 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003479 // The camera id is visible to the client. Fine to send torch
3480 // callback.
3481 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3482 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3483 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003484 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003485 }
3486
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003487 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003488}
Ruben Brunkcc776712015-02-17 20:18:47 -08003489
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003490Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003491 ATRACE_CALL();
3492
Igor Murashkinbfc99152013-02-27 12:55:20 -08003493 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3494
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003495 if (listener == 0) {
3496 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003497 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003498 }
3499
Igor Murashkinbfc99152013-02-27 12:55:20 -08003500 Mutex::Autolock lock(mServiceLock);
3501
Ruben Brunkcc776712015-02-17 20:18:47 -08003502 {
3503 Mutex::Autolock lock(mStatusListenerLock);
3504 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003505 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003506 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003507 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003508 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003509 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003510 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003511 }
3512 }
3513
3514 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3515 __FUNCTION__, listener.get());
3516
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003517 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003518}
3519
Austin Borgered99f642023-06-01 16:51:35 -07003520Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003521
3522 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003523 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3524
3525 if (parameters == NULL) {
3526 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003527 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003528 }
3529
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003530 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003531
3532 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003533 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003534 // Error logged by caller
3535 return ret;
3536 }
3537
3538 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003539
Austin Borgered99f642023-06-01 16:51:35 -07003540 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003541
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003542 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003543}
3544
Austin Borgered99f642023-06-01 16:51:35 -07003545Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003546 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003547 ATRACE_CALL();
3548
malikakashedb38962023-09-06 00:03:35 +00003549 const std::string cameraId = resolveCameraId(
3550 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003551
Austin Borgered99f642023-06-01 16:51:35 -07003552 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003553
3554 switch (apiVersion) {
3555 case API_VERSION_1:
3556 case API_VERSION_2:
3557 break;
3558 default:
Austin Borgered99f642023-06-01 16:51:35 -07003559 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3560 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3561 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003562 }
3563
Austin Borger18b30a72022-10-27 12:20:29 -07003564 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003565 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003566 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003567 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3568 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3569 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003570 }
3571 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3572 int deviceVersion = deviceVersionAndTransport.first;
3573 switch (deviceVersion) {
3574 case CAMERA_DEVICE_API_VERSION_1_0:
3575 case CAMERA_DEVICE_API_VERSION_3_0:
3576 case CAMERA_DEVICE_API_VERSION_3_1:
3577 if (apiVersion == API_VERSION_2) {
3578 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003579 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003580 *isSupported = false;
3581 } else { // if (apiVersion == API_VERSION_1) {
3582 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003583 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003584 *isSupported = true;
3585 }
3586 break;
3587 case CAMERA_DEVICE_API_VERSION_3_2:
3588 case CAMERA_DEVICE_API_VERSION_3_3:
3589 case CAMERA_DEVICE_API_VERSION_3_4:
3590 case CAMERA_DEVICE_API_VERSION_3_5:
3591 case CAMERA_DEVICE_API_VERSION_3_6:
3592 case CAMERA_DEVICE_API_VERSION_3_7:
3593 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003594 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003595 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003596 break;
3597 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003598 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3599 deviceVersion, cameraId.c_str());
3600 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3601 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003602 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003603 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003604 } else {
3605 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003606 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003607 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003608}
3609
Austin Borgered99f642023-06-01 16:51:35 -07003610Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003611 /*out*/ bool *isSupported) {
3612 ATRACE_CALL();
3613
malikakashedb38962023-09-06 00:03:35 +00003614 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3615 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003616
Austin Borgered99f642023-06-01 16:51:35 -07003617 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3618 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003619
3620 return Status::ok();
3621}
3622
Cliff Wud8cae102021-03-11 01:37:42 +08003623Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003624 const std::string& packageName, const std::string& internalCamId,
3625 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003626 const sp<ICameraInjectionCallback>& callback,
3627 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003628 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003629 ATRACE_CALL();
3630
Austin Borgered99f642023-06-01 16:51:35 -07003631 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003632 const int pid = CameraThreadState::getCallingPid();
3633 const int uid = CameraThreadState::getCallingUid();
3634 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3635 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3636 "Permission Denial: no permission to inject camera");
3637 }
3638
3639 ALOGV(
3640 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3641 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003642 __FUNCTION__, packageName.c_str(),
3643 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003644
Cliff Wud3a05312021-04-26 23:07:31 +08003645 {
3646 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003647 mInjectionInternalCamId = internalCamId;
3648 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003649 mInjectionStatusListener->addListener(callback);
3650 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003651 status_t res = NO_ERROR;
3652 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3653 // If the client already exists, we can directly connect to the camera device through the
3654 // client's injectCamera(), otherwise we need to wait until the client is established
3655 // (execute connectHelper()) before injecting the camera to the camera device.
3656 if (clientDescriptor != nullptr) {
3657 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003658 sp<BasicClient> clientSp = clientDescriptor->getValue();
3659 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3660 if(res != OK) {
3661 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3662 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003663 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003664 }
3665 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003666 if(res != OK) {
3667 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3668 }
3669 } else {
3670 mInjectionInitPending = true;
3671 }
3672 }
Cliff Wud8cae102021-03-11 01:37:42 +08003673
Cliff Wud3a05312021-04-26 23:07:31 +08003674 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003675}
3676
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003677Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003678 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003679 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3680 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3681 return Status::ok();
3682}
3683
Ruben Brunkcc776712015-02-17 20:18:47 -08003684void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003685 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003686 for (auto& i : mActiveClientManager.getAll()) {
3687 auto clientSp = i->getValue();
3688 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003689 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003690 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003691 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003692 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003693 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003694}
3695
Ruben Brunkcc776712015-02-17 20:18:47 -08003696bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003697 bool ret = false;
3698 {
3699 // Acquire mServiceLock and prevent other clients from connecting
3700 std::unique_ptr<AutoConditionLock> lock =
3701 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003702
Igor Murashkin634a5152013-02-20 17:15:11 -08003703
Ruben Brunkcc776712015-02-17 20:18:47 -08003704 std::vector<sp<BasicClient>> evicted;
3705 for (auto& i : mActiveClientManager.getAll()) {
3706 auto clientSp = i->getValue();
3707 if (clientSp.get() == nullptr) {
3708 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3709 mActiveClientManager.remove(i);
3710 continue;
3711 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003712 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003713 mActiveClientManager.remove(i);
3714 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003715
Ruben Brunkcc776712015-02-17 20:18:47 -08003716 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003717 clientSp->notifyError(
3718 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003720 }
3721 }
3722
Ruben Brunkcc776712015-02-17 20:18:47 -08003723 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3724 // other clients from connecting in mServiceLockWrapper if held
3725 mServiceLock.unlock();
3726
Ruben Brunk36597b22015-03-20 22:15:57 -07003727 // Do not clear caller identity, remote caller should be client proccess
3728
Ruben Brunkcc776712015-02-17 20:18:47 -08003729 for (auto& i : evicted) {
3730 if (i.get() != nullptr) {
3731 i->disconnect();
3732 ret = true;
3733 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003734 }
3735
Ruben Brunkcc776712015-02-17 20:18:47 -08003736 // Reacquire mServiceLock
3737 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003738
Ruben Brunkcc776712015-02-17 20:18:47 -08003739 } // lock is destroyed, allow further connect calls
3740
3741 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003742}
3743
Ruben Brunkcc776712015-02-17 20:18:47 -08003744std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003745 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003746 std::shared_ptr<CameraState> state;
3747 {
3748 Mutex::Autolock lock(mCameraStatesLock);
3749 auto iter = mCameraStates.find(cameraId);
3750 if (iter != mCameraStates.end()) {
3751 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 }
3753 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755}
3756
Austin Borgered99f642023-06-01 16:51:35 -07003757sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 // Remove from active clients list
3759 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3760 if (clientDescriptorPtr == nullptr) {
3761 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003762 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003763 return sp<BasicClient>{nullptr};
3764 }
3765
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003766 sp<BasicClient> client = clientDescriptorPtr->getValue();
3767 if (client.get() != nullptr) {
3768 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3769 }
3770 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003771}
3772
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003773void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003774 // Acquire mServiceLock and prevent other clients from connecting
3775 std::unique_ptr<AutoConditionLock> lock =
3776 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3777
Ruben Brunk6267b532015-04-30 17:44:07 -07003778 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003779 for (size_t i = 0; i < newUserIds.size(); i++) {
3780 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003781 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003782 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003783 return;
3784 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003785 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003786 }
3787
Ruben Brunka8ca9152015-04-07 14:23:40 -07003788
Ruben Brunk6267b532015-04-30 17:44:07 -07003789 if (newAllowedUsers == mAllowedUsers) {
3790 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3791 return;
3792 }
3793
3794 logUserSwitch(mAllowedUsers, newAllowedUsers);
3795
3796 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003797
3798 // Current user has switched, evict all current clients.
3799 std::vector<sp<BasicClient>> evicted;
3800 for (auto& i : mActiveClientManager.getAll()) {
3801 auto clientSp = i->getValue();
3802
3803 if (clientSp.get() == nullptr) {
3804 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3805 continue;
3806 }
3807
Ruben Brunk6267b532015-04-30 17:44:07 -07003808 // Don't evict clients that are still allowed.
3809 uid_t clientUid = clientSp->getClientUid();
3810 userid_t clientUserId = multiuser_get_user_id(clientUid);
3811 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3812 continue;
3813 }
3814
Ruben Brunk36597b22015-03-20 22:15:57 -07003815 evicted.push_back(clientSp);
3816
Ruben Brunk36597b22015-03-20 22:15:57 -07003817 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003818 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003819
Ruben Brunk36597b22015-03-20 22:15:57 -07003820 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003821 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003822 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003823 " to user switch.", i->getKey().c_str(),
3824 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003825 i->getOwnerId(), i->getPriority().getScore(),
3826 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003827
3828 }
3829
3830 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3831 // blocking other clients from connecting in mServiceLockWrapper if held.
3832 mServiceLock.unlock();
3833
3834 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003835 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003836
3837 for (auto& i : evicted) {
3838 i->disconnect();
3839 }
3840
Jayant Chowdhary12361932018-08-27 14:46:13 -07003841 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003842
3843 // Reacquire mServiceLock
3844 mServiceLock.lock();
3845}
Ruben Brunkcc776712015-02-17 20:18:47 -08003846
Austin Borgered99f642023-06-01 16:51:35 -07003847void CameraService::logEvent(const std::string &event) {
3848 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003849 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003850 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003851 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003852 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003853 mEventLog.add(msg);
3854 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3855 // Error event not added to the dumpsys log before
3856 mEventLog.add(msg);
3857 sServiceErrorEventSet.insert(msg);
3858 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859}
3860
Austin Borgered99f642023-06-01 16:51:35 -07003861void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3862 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003863 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003864 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3865 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003866}
3867
Austin Borgered99f642023-06-01 16:51:35 -07003868void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3869 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003870 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003871 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3872 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003873}
3874
Austin Borgered99f642023-06-01 16:51:35 -07003875void CameraService::logConnected(const std::string &cameraId, int clientPid,
3876 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003877 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003878 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3879 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003880}
3881
Austin Borgered99f642023-06-01 16:51:35 -07003882void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3883 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003884 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003885 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3886 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003887}
3888
Austin Borgered99f642023-06-01 16:51:35 -07003889void CameraService::logRejected(const std::string &cameraId, int clientPid,
3890 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003891 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003892 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3893 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003894}
3895
Austin Borgered99f642023-06-01 16:51:35 -07003896void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3897 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003898 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003899 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3900 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003901}
3902
Ruben Brunk6267b532015-04-30 17:44:07 -07003903void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3904 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003905 std::string newUsers = toString(newUserIds);
3906 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003907 if (oldUsers.size() == 0) {
3908 oldUsers = "<None>";
3909 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003910 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003911 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3912 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003913}
3914
Austin Borgered99f642023-06-01 16:51:35 -07003915void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003916 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003917 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003918}
3919
Austin Borgered99f642023-06-01 16:51:35 -07003920void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003921 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003922 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003923}
3924
Austin Borgered99f642023-06-01 16:51:35 -07003925void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003926 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003927 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003928}
3929
Austin Borgered99f642023-06-01 16:51:35 -07003930void CameraService::logServiceError(const std::string &msg, int errorCode) {
3931 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3932 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003933}
3934
Ruben Brunk36597b22015-03-20 22:15:57 -07003935status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3936 uint32_t flags) {
3937
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 // Permission checks
3939 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003940 case SHELL_COMMAND_TRANSACTION: {
3941 int in = data.readFileDescriptor();
3942 int out = data.readFileDescriptor();
3943 int err = data.readFileDescriptor();
3944 int argc = data.readInt32();
3945 Vector<String16> args;
3946 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3947 args.add(data.readString16());
3948 }
3949 sp<IBinder> unusedCallback;
3950 sp<IResultReceiver> resultReceiver;
3951 status_t status;
3952 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3953 return status;
3954 }
3955 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3956 return status;
3957 }
3958 status = shellCommand(in, out, err, args);
3959 if (resultReceiver != nullptr) {
3960 resultReceiver->send(status);
3961 }
3962 return NO_ERROR;
3963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 }
3965
3966 return BnCameraService::onTransact(code, data, reply, flags);
3967}
3968
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969// We share the media players for shutter and recording sound for all clients.
3970// A reference count is kept to determine when we will actually release the
3971// media players.
3972
Jaekyun Seokef498052018-03-23 13:09:44 +09003973sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3974 sp<MediaPlayer> mp = new MediaPlayer();
3975 status_t error;
3976 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003977 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003978 error = mp->prepare();
3979 }
3980 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003981 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003982 mp->disconnect();
3983 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003984 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985 }
3986 return mp;
3987}
3988
username5755fea2018-12-27 09:48:08 +08003989void CameraService::increaseSoundRef() {
3990 Mutex::Autolock lock(mSoundLock);
3991 mSoundRef++;
3992}
3993
3994void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003995 ATRACE_CALL();
3996
username5755fea2018-12-27 09:48:08 +08003997 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3998 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3999 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4000 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4001 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4002 }
4003 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4004 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4005 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4006 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004007 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004008 }
4009 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4010 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4011 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4012 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4013 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015}
4016
username5755fea2018-12-27 09:48:08 +08004017void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004019 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 if (--mSoundRef) return;
4021
4022 for (int i = 0; i < NUM_SOUNDS; i++) {
4023 if (mSoundPlayer[i] != 0) {
4024 mSoundPlayer[i]->disconnect();
4025 mSoundPlayer[i].clear();
4026 }
4027 }
4028}
4029
4030void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004031 ATRACE_CALL();
4032
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004034 if (kind < 0 || kind >= NUM_SOUNDS) {
4035 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4036 return;
4037 }
4038
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004040 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 sp<MediaPlayer> player = mSoundPlayer[kind];
4042 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004043 player->seekTo(0);
4044 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045 }
4046}
4047
4048// ----------------------------------------------------------------------------
4049
4050CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004051 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07004052 const std::string& clientPackageName, bool systemNativeClient,
4053 const std::optional<std::string>& clientFeatureId,
4054 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004055 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004056 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004057 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004058 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004059 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004060 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004061 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004062 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004063 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004064 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004065{
Jayant Chowdhary12361932018-08-27 14:46:13 -07004066 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004067 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004069 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070
username5755fea2018-12-27 09:48:08 +08004071 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004072
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004073 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074}
4075
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076// tear down the client
4077CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004078 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004079 mDestructionStarted = true;
4080
username5755fea2018-12-27 09:48:08 +08004081 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004082 // unconditionally disconnect. function is idempotent
4083 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084}
4085
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004086sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4087
Igor Murashkin634a5152013-02-20 17:15:11 -08004088CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004089 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07004090 const std::string& clientPackageName, bool nativeClient,
4091 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004092 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004093 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004094 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004095 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004096 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4097 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004098 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004099 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004100 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004101 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004102 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004103 mRemoteBinder(remoteCallback),
4104 mOpsActive(false),
4105 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004106{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004107 if (sCameraService == nullptr) {
4108 sCameraService = cameraService;
4109 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004110
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004111 // There are 2 scenarios in which a client won't have AppOps operations
4112 // (both scenarios : native clients)
4113 // 1) It's an system native client*, the package name will be empty
4114 // and it will return from this function in the previous if condition
4115 // (This is the same as the previously existing behavior).
4116 // 2) It is a system native client, but its package name has been
4117 // modified for debugging, however it still must not use AppOps since
4118 // the package name is not a real one.
4119 //
4120 // * system native client - native client with UID < AID_APP_START. It
4121 // doesn't exclude clients not on the system partition.
4122 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004123 mAppOpsManager = std::make_unique<AppOpsManager>();
4124 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004125
Charles Chenf075f082024-03-04 23:32:55 +00004126 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004127}
4128
4129CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004130 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004131 mDestructionStarted = true;
4132}
4133
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004134binder::Status CameraService::BasicClient::disconnect() {
4135 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004136 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004137 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004138 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004139 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004140
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004141 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004142 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004143 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004144 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004145
4146 sp<IBinder> remote = getRemote();
4147 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004148 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004149 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004150
4151 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004152 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004153 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004154 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004155 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004156
Igor Murashkincba2c162013-03-20 15:56:31 -07004157 // client shouldn't be able to call into us anymore
4158 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004159
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004160 const auto& mActivityManager = getActivityManager();
4161 if (mActivityManager) {
4162 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4163 CameraThreadState::getCallingUid(),
4164 CameraThreadState::getCallingPid());
4165 }
4166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004167 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004168}
4169
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004170status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4171 // No dumping of clients directly over Binder,
4172 // must go through CameraService::dump
4173 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004174 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004175 return OK;
4176}
4177
Austin Borgered99f642023-06-01 16:51:35 -07004178status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004179 // Can't watch tags directly, must go through CameraService::startWatchingTags
4180 return OK;
4181}
4182
4183status_t CameraService::BasicClient::stopWatchingTags(int) {
4184 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4185 return OK;
4186}
4187
4188status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4189 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4190 return OK;
4191}
4192
Austin Borgered99f642023-06-01 16:51:35 -07004193std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004194 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004195}
4196
Emilian Peev8b64f282021-03-25 16:49:57 -07004197int CameraService::BasicClient::getCameraFacing() const {
4198 return mCameraFacing;
4199}
4200
4201int CameraService::BasicClient::getCameraOrientation() const {
4202 return mOrientation;
4203}
Ruben Brunkcc776712015-02-17 20:18:47 -08004204
4205int CameraService::BasicClient::getClientPid() const {
4206 return mClientPid;
4207}
4208
Ruben Brunk6267b532015-04-30 17:44:07 -07004209uid_t CameraService::BasicClient::getClientUid() const {
4210 return mClientUid;
4211}
4212
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004213bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4214 // Defaults to API2.
4215 return level == API_2;
4216}
4217
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004218status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004219 {
4220 Mutex::Autolock l(mAudioRestrictionLock);
4221 mAudioRestriction = mode;
4222 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004223 sCameraService->updateAudioRestriction();
4224 return OK;
4225}
4226
4227int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004228 return sCameraService->updateAudioRestriction();
4229}
4230
4231int32_t CameraService::BasicClient::getAudioRestriction() const {
4232 Mutex::Autolock l(mAudioRestrictionLock);
4233 return mAudioRestriction;
4234}
4235
4236bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4237 switch (mode) {
4238 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4239 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4240 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4241 return true;
4242 default:
4243 return false;
4244 }
4245}
4246
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004247status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4248 if (mode == AppOpsManager::MODE_ERRORED) {
4249 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004250 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004251 return PERMISSION_DENIED;
4252 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4253 // If the calling Uid is trusted (a native service), the AppOpsManager could
4254 // return MODE_IGNORED. Do not treat such case as error.
4255 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4256 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004257
4258 bool isCameraPrivacyEnabled;
4259 if (flags::camera_privacy_allowlist()) {
4260 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4261 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4262 } else {
4263 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004264 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004265 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004266 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4267 // We prefer to successfully open the camera and perform camera muting
4268 // or blocking in connectHelper as handleAppOpMode can be called before the
4269 // connection has been fully established and at that time camera muting
4270 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004271 if (!isUidActive || !isCameraPrivacyEnabled) {
4272 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004273 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004274 // Return the same error as for device policy manager rejection
4275 return -EACCES;
4276 }
4277 }
4278 return OK;
4279}
4280
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004281status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004282 ATRACE_CALL();
4283
Igor Murashkine6800ce2013-03-04 17:25:57 -08004284 {
4285 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004286 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004287 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004288 if (mAppOpsManager != nullptr) {
4289 // Notify app ops that the camera is not available
4290 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004291
4292 if (flags::watch_foreground_changes()) {
4293 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4294 toString16(mClientPackageName),
4295 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4296 } else {
4297 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004298 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004299 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004300
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004301 // Just check for camera acccess here on open - delay startOp until
4302 // camera frames start streaming in startCameraStreamingOps
4303 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004304 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004305 status_t res = handleAppOpMode(mode);
4306 if (res != OK) {
4307 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004308 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004309 }
4310
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004311 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004312
4313 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004314 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004315
Austin Borgerdddb7552023-03-30 17:53:01 -07004316 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004317
Shuzhen Wang695044d2020-03-06 09:02:23 -08004318 // Notify listeners of camera open/close status
4319 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4320
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004321 return OK;
4322}
4323
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004324status_t CameraService::BasicClient::startCameraStreamingOps() {
4325 ATRACE_CALL();
4326
4327 if (!mOpsActive) {
4328 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4329 return INVALID_OPERATION;
4330 }
4331 if (mOpsStreaming) {
4332 ALOGV("%s: Streaming already active!", __FUNCTION__);
4333 return OK;
4334 }
4335
4336 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004337 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004338
4339 if (mAppOpsManager != nullptr) {
4340 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004341 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4342 toString16(mClientFeatureId),
4343 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004344 status_t res = handleAppOpMode(mode);
4345 if (res != OK) {
4346 return res;
4347 }
4348 }
4349
4350 mOpsStreaming = true;
4351
4352 return OK;
4353}
4354
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004355status_t CameraService::BasicClient::noteAppOp() {
4356 ATRACE_CALL();
4357
4358 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004359 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004360
4361 // noteAppOp is only used for when camera mute is not supported, in order
4362 // to trigger the sensor privacy "Unblock" dialog
4363 if (mAppOpsManager != nullptr) {
4364 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004365 toString16(mClientPackageName), toString16(mClientFeatureId),
4366 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004367 status_t res = handleAppOpMode(mode);
4368 if (res != OK) {
4369 return res;
4370 }
4371 }
4372
4373 return OK;
4374}
4375
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004376status_t CameraService::BasicClient::finishCameraStreamingOps() {
4377 ATRACE_CALL();
4378
4379 if (!mOpsActive) {
4380 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4381 return INVALID_OPERATION;
4382 }
4383 if (!mOpsStreaming) {
4384 ALOGV("%s: Streaming not active!", __FUNCTION__);
4385 return OK;
4386 }
4387
4388 if (mAppOpsManager != nullptr) {
4389 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004390 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004391 mOpsStreaming = false;
4392 }
4393
4394 return OK;
4395}
4396
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004397status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004398 ATRACE_CALL();
4399
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004400 if (mOpsStreaming) {
4401 // Make sure we've notified everyone about camera stopping
4402 finishCameraStreamingOps();
4403 }
4404
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004405 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004406 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004407 mOpsActive = false;
4408
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004409 // This function is called when a client disconnects. This should
4410 // release the camera, but actually only if it was in a proper
4411 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004412 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004413 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004414
Ruben Brunkcc776712015-02-17 20:18:47 -08004415 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004416 sCameraService->updateStatus(StatusInternal::PRESENT,
4417 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004418 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004419 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004420 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4421 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004422 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004423 mOpsCallback.clear();
4424
Austin Borgerdddb7552023-03-30 17:53:01 -07004425 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004426
Shuzhen Wang695044d2020-03-06 09:02:23 -08004427 // Notify listeners of camera open/close status
4428 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4429
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004430 return OK;
4431}
4432
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004433void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004434 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004435 if (mAppOpsManager == nullptr) {
4436 return;
4437 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004438 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004439 if (op != AppOpsManager::OP_CAMERA) {
4440 ALOGW("Unexpected app ops notification received: %d", op);
4441 return;
4442 }
4443
4444 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004445 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004446 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004447 ALOGV("checkOp returns: %d, %s ", res,
4448 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4449 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4450 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4451 "UNKNOWN");
4452
Shuzhen Wang64900852021-02-05 09:03:29 -08004453 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004454 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4455 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004456 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004457 } else if (res == AppOpsManager::MODE_IGNORED) {
4458 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004459
Austin Borgerca1e0062023-06-28 11:32:55 -07004460 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4461 // If not visible, but still active, then we want to block instead of muting the camera.
4462 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4463 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4464
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004465 bool isCameraPrivacyEnabled;
4466 if (flags::camera_privacy_allowlist()) {
4467 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4468 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4469 } else {
4470 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004471 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004472 }
4473
4474 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004475 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4476 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4477 isCameraPrivacyEnabled);
4478 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4479 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4480 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004481 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004482 if (flags::watch_foreground_changes()) {
4483 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4484 setCameraMute(true);
4485 } else {
4486 block();
4487 }
4488 } else {
4489 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4490 setCameraMute(true);
4491 } else if (!isUidActive
4492 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4493 block();
4494 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004495 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004496 }
Evan Severson09ab4002021-02-10 14:15:19 -08004497 } else if (res == AppOpsManager::MODE_ALLOWED) {
4498 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004499 }
4500}
4501
Svet Ganova453d0d2018-01-11 15:37:58 -08004502void CameraService::BasicClient::block() {
4503 ATRACE_CALL();
4504
4505 // Reset the client PID to allow server-initiated disconnect,
4506 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004507 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004508 CaptureResultExtras resultExtras; // a dummy result (invalid)
4509 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4510 disconnect();
4511}
4512
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513// ----------------------------------------------------------------------------
4514
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004515void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004516 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004517 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004518 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4519 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4520 api1ErrorCode = CAMERA_ERROR_DISABLED;
4521 }
4522 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004523 } else {
4524 ALOGE("mRemoteCallback is NULL!!");
4525 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004526}
4527
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004528// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004529binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004530 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004531 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004532}
4533
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004534bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4535 return level == API_1;
4536}
4537
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004538CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4539 mClient(client) {
4540}
4541
4542void CameraService::Client::OpsCallback::opChanged(int32_t op,
4543 const String16& packageName) {
4544 sp<BasicClient> client = mClient.promote();
4545 if (client != NULL) {
4546 client->opChanged(op, packageName);
4547 }
4548}
4549
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004551// UidPolicy
4552// ----------------------------------------------------------------------------
4553
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004554void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004555 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004556 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004557
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004558 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004559 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004560 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004561 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004562 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4563 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004564 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004565 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004566 if (res == OK) {
4567 mRegistered = true;
4568 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004569 } else {
4570 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004571 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004572}
4573
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004574void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004575 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004576 return;
4577 }
4578
4579 registerWithActivityManager();
4580}
4581
4582void CameraService::UidPolicy::registerSelf() {
4583 // Use check service to see if the activity service is available
4584 // If not available then register for notifications, instead of blocking
4585 // till the service is ready
4586 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004587 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004588 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004589 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004590 } else {
4591 registerWithActivityManager();
4592 }
4593}
4594
Svet Ganova453d0d2018-01-11 15:37:58 -08004595void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004596 Mutex::Autolock _l(mUidLock);
4597
Steven Moreland2f348142019-07-02 15:59:07 -07004598 mAm.unregisterUidObserver(this);
4599 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004600 mRegistered = false;
4601 mActiveUids.clear();
4602 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004603}
4604
4605void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4606 onUidIdle(uid, disabled);
4607}
4608
4609void CameraService::UidPolicy::onUidActive(uid_t uid) {
4610 Mutex::Autolock _l(mUidLock);
4611 mActiveUids.insert(uid);
4612}
4613
4614void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4615 bool deleted = false;
4616 {
4617 Mutex::Autolock _l(mUidLock);
4618 if (mActiveUids.erase(uid) > 0) {
4619 deleted = true;
4620 }
4621 }
4622 if (deleted) {
4623 sp<CameraService> service = mService.promote();
4624 if (service != nullptr) {
4625 service->blockClientsForUid(uid);
4626 }
4627 }
4628}
4629
Emilian Peev53722fa2019-02-22 17:47:20 -08004630void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004631 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004632 bool procStateChange = false;
4633 {
4634 Mutex::Autolock _l(mUidLock);
4635 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4636 mMonitoredUids[uid].procState != procState) {
4637 mMonitoredUids[uid].procState = procState;
4638 procStateChange = true;
4639 }
4640 }
4641
4642 if (procStateChange) {
4643 sp<CameraService> service = mService.promote();
4644 if (service != nullptr) {
4645 service->notifyMonitoredUids();
4646 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004647 }
4648}
4649
Austin Borgerdddb7552023-03-30 17:53:01 -07004650/**
4651 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4652 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4653 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4654 * monitoredUids. If it is revised above some other monitoredUid, signal
4655 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4656 * foreground apps in split screen - state changes will capture all other cases.
4657 */
4658void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4659 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004660 {
4661 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004662 auto it = mMonitoredUids.find(uid);
4663
4664 if (it != mMonitoredUids.end()) {
4665 if (it->second.hasCamera) {
4666 for (auto &monitoredUid : mMonitoredUids) {
4667 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004668 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004669 notifyUidSet.emplace(monitoredUid.first);
4670 }
4671 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004672 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004673 notifyUidSet.emplace(uid);
4674 } else {
4675 for (auto &monitoredUid : mMonitoredUids) {
4676 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004677 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004678 notifyUidSet.emplace(uid);
4679 }
4680 }
4681 }
4682 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004683 }
4684 }
4685
Austin Borgerdddb7552023-03-30 17:53:01 -07004686 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004687 sp<CameraService> service = mService.promote();
4688 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004689 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004690 }
4691 }
4692}
4693
Austin Borgerdddb7552023-03-30 17:53:01 -07004694/**
4695 * Register a uid for monitoring, and note whether it owns a camera.
4696 */
4697void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004698 Mutex::Autolock _l(mUidLock);
4699 auto it = mMonitoredUids.find(uid);
4700 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004701 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004702 } else {
Austin Borger65577682022-02-17 00:25:43 +00004703 MonitoredUid monitoredUid;
4704 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004705 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004706 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004707 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004708 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004709 if (res != OK) {
4710 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4711 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004712 }
4713
4714 if (openCamera) {
4715 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004716 }
4717}
4718
Austin Borgerdddb7552023-03-30 17:53:01 -07004719/**
4720 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4721 */
4722void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004723 Mutex::Autolock _l(mUidLock);
4724 auto it = mMonitoredUids.find(uid);
4725 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004726 it->second.refCount--;
4727 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004728 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004729 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004730 if (res != OK) {
4731 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4732 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004733 } else if (closeCamera) {
4734 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004735 }
4736 } else {
4737 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4738 }
4739}
4740
Austin Borgered99f642023-06-01 16:51:35 -07004741bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004742 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004743 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004744}
4745
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004746static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4747static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004748
Austin Borgered99f642023-06-01 16:51:35 -07004749bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004750 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004751 // If activity manager is unreachable, assume everything is active
4752 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004753 return true;
4754 }
4755 auto it = mOverrideUids.find(uid);
4756 if (it != mOverrideUids.end()) {
4757 return it->second;
4758 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004759 bool active = mActiveUids.find(uid) != mActiveUids.end();
4760 if (!active) {
4761 // We want active UIDs to always access camera with their first attempt since
4762 // there is no guarantee the app is robustly written and would retry getting
4763 // the camera on failure. The inverse case is not a problem as we would take
4764 // camera away soon once we get the callback that the uid is no longer active.
4765 ActivityManager am;
4766 // Okay to access with a lock held as UID changes are dispatched without
4767 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004768 int64_t startTimeMillis = 0;
4769 do {
4770 // TODO: Fix this b/109950150!
4771 // Okay this is a hack. There is a race between the UID turning active and
4772 // activity being resumed. The proper fix is very risky, so we temporary add
4773 // some polling which should happen pretty rarely anyway as the race is hard
4774 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004775 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004776 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004777 if (active) {
4778 break;
4779 }
4780 if (startTimeMillis <= 0) {
4781 startTimeMillis = uptimeMillis();
4782 }
4783 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004784 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004785 if (remainingTimeMillis <= 0) {
4786 break;
4787 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004788 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4789
4790 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004791 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004792 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004793 } while (true);
4794
Svet Ganov7b4ab782018-03-25 12:48:10 -07004795 if (active) {
4796 // Now that we found out the UID is actually active, cache that
4797 mActiveUids.insert(uid);
4798 }
4799 }
4800 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004801}
4802
Varun Shahb42f1eb2019-04-16 14:45:13 -07004803int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4804 Mutex::Autolock _l(mUidLock);
4805 return getProcStateLocked(uid);
4806}
4807
4808int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4809 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4810 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004811 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004812 }
4813 return procState;
4814}
4815
Austin Borgered99f642023-06-01 16:51:35 -07004816void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4817 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004818 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004819}
4820
Austin Borgered99f642023-06-01 16:51:35 -07004821void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004822 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004823}
4824
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004825void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4826 Mutex::Autolock _l(mUidLock);
4827 ALOGV("UidPolicy: ActivityManager has died");
4828 mRegistered = false;
4829 mActiveUids.clear();
4830}
4831
Austin Borgered99f642023-06-01 16:51:35 -07004832void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004833 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004834 bool wasActive = false;
4835 bool isActive = false;
4836 {
4837 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004838 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004839 mOverrideUids.erase(uid);
4840 if (insert) {
4841 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4842 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004843 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004844 }
4845 if (wasActive != isActive && !isActive) {
4846 sp<CameraService> service = mService.promote();
4847 if (service != nullptr) {
4848 service->blockClientsForUid(uid);
4849 }
4850 }
4851}
4852
4853// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004854// SensorPrivacyPolicy
4855// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004856
4857void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4858{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004859 Mutex::Autolock _l(mSensorPrivacyLock);
4860 if (mRegistered) {
4861 return;
4862 }
Evan Severson09ab4002021-02-10 14:15:19 -08004863 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004864 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004865 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004866 mSpm.addToggleSensorPrivacyListener(this);
4867 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004868 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004869 if (flags::camera_privacy_allowlist()) {
4870 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4871 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4872 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4873 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004874 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004875 if (res == OK) {
4876 mRegistered = true;
4877 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4878 }
4879}
4880
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004881void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4882 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004883 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004884 return;
4885 }
4886
4887 registerWithSensorPrivacyManager();
4888}
4889
4890void CameraService::SensorPrivacyPolicy::registerSelf() {
4891 // Use checkservice to see if the sensor_privacy service is available
4892 // If service is not available then register for notification
4893 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004894 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004895 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004896 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004897 } else {
4898 registerWithSensorPrivacyManager();
4899 }
4900}
4901
Michael Grooverd1d435a2018-12-18 17:39:42 -08004902void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4903 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004904 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004905 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004906 mSpm.removeToggleSensorPrivacyListener(this);
4907 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004908 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004909 mRegistered = false;
4910 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4911}
4912
4913bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004914 if (!mRegistered) {
4915 registerWithSensorPrivacyManager();
4916 }
4917
Michael Grooverd1d435a2018-12-18 17:39:42 -08004918 Mutex::Autolock _l(mSensorPrivacyLock);
4919 return mSensorPrivacyEnabled;
4920}
4921
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004922int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4923 if (!mRegistered) {
4924 registerWithSensorPrivacyManager();
4925 }
4926
4927 Mutex::Autolock _l(mSensorPrivacyLock);
4928 return mCameraPrivacyState;
4929}
4930
Evan Seversond0b69922022-01-27 10:47:34 -08004931bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004932 if (!hasCameraPrivacyFeature()) {
4933 return false;
4934 }
Evan Seversond0b69922022-01-27 10:47:34 -08004935 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004936}
4937
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004938bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4939 if (!hasCameraPrivacyFeature()) {
4940 return SensorPrivacyManager::DISABLED;
4941 }
4942 return mSpm.isCameraPrivacyEnabled(packageName);
4943}
4944
Evan Seversond0b69922022-01-27 10:47:34 -08004945binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004946 int toggleType, int sensor, bool enabled) {
4947 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4948 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4949 {
4950 Mutex::Autolock _l(mSensorPrivacyLock);
4951 mSensorPrivacyEnabled = enabled;
4952 }
4953 // if sensor privacy is enabled then block all clients from accessing the camera
4954 if (enabled) {
4955 sp<CameraService> service = mService.promote();
4956 if (service != nullptr) {
4957 service->blockAllClients();
4958 }
4959 }
4960 }
4961 return binder::Status::ok();
4962}
4963
4964binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4965 int, int sensor, int state) {
4966 if (!flags::camera_privacy_allowlist()
4967 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4968 return binder::Status::ok();
4969 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004970 {
4971 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004972 mCameraPrivacyState = state;
4973 }
4974 sp<CameraService> service = mService.promote();
4975 if (!service) {
4976 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004977 }
4978 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004979 if (state == SensorPrivacyManager::ENABLED) {
4980 service->blockAllClients();
4981 } else if ((state == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_APPS)
4982 || (state == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS)
4983 || (state == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS)) {
4984 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004985 }
4986 return binder::Status::ok();
4987}
4988
4989void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4990 Mutex::Autolock _l(mSensorPrivacyLock);
4991 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4992 mRegistered = false;
4993}
4994
Evan Severson09ab4002021-02-10 14:15:19 -08004995bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004996 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4997 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4998 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4999 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5000 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005001}
5002
Michael Grooverd1d435a2018-12-18 17:39:42 -08005003// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005004// CameraState
5005// ----------------------------------------------------------------------------
5006
Austin Borgered99f642023-06-01 16:51:35 -07005007CameraService::CameraState::CameraState(const std::string& id, int cost,
5008 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005009 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005010 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005011 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005012
5013CameraService::CameraState::~CameraState() {}
5014
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005015CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005016 Mutex::Autolock lock(mStatusLock);
5017 return mStatus;
5018}
5019
Austin Borgered99f642023-06-01 16:51:35 -07005020std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005021 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005022 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005023 return res;
5024}
5025
Ruben Brunkcc776712015-02-17 20:18:47 -08005026CameraParameters CameraService::CameraState::getShimParams() const {
5027 return mShimParams;
5028}
5029
5030void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5031 mShimParams = params;
5032}
5033
5034int CameraService::CameraState::getCost() const {
5035 return mCost;
5036}
5037
Austin Borgered99f642023-06-01 16:51:35 -07005038std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005039 return mConflicting;
5040}
5041
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005042SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5043 return mSystemCameraKind;
5044}
5045
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005046bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5047 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5048 != mPhysicalCameras.end();
5049}
5050
Austin Borgered99f642023-06-01 16:51:35 -07005051bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005052 Mutex::Autolock lock(mStatusLock);
5053 auto result = mUnavailablePhysicalIds.insert(physicalId);
5054 return result.second;
5055}
5056
Austin Borgered99f642023-06-01 16:51:35 -07005057bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005058 Mutex::Autolock lock(mStatusLock);
5059 auto count = mUnavailablePhysicalIds.erase(physicalId);
5060 return count > 0;
5061}
5062
Austin Borgered99f642023-06-01 16:51:35 -07005063void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005064 Mutex::Autolock lock(mStatusLock);
5065 mClientPackage = clientPackage;
5066}
5067
Austin Borgered99f642023-06-01 16:51:35 -07005068std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005069 Mutex::Autolock lock(mStatusLock);
5070 return mClientPackage;
5071}
5072
Ruben Brunkcc776712015-02-17 20:18:47 -08005073// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005074// ClientEventListener
5075// ----------------------------------------------------------------------------
5076
5077void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005078 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005079 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005080 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005081 if (basicClient.get() != nullptr) {
5082 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005083 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005084 static_cast<int>(basicClient->getClientUid()));
5085 }
5086}
5087
5088void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005089 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005090 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005091 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005092 if (basicClient.get() != nullptr) {
5093 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005094 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005095 static_cast<int>(basicClient->getClientUid()));
5096 }
5097}
5098
5099
5100// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005101// CameraClientManager
5102// ----------------------------------------------------------------------------
5103
Ruben Brunk99e69712015-05-26 17:25:07 -07005104CameraService::CameraClientManager::CameraClientManager() {
5105 setListener(std::make_shared<ClientEventListener>());
5106}
5107
Ruben Brunkcc776712015-02-17 20:18:47 -08005108CameraService::CameraClientManager::~CameraClientManager() {}
5109
5110sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005111 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005112 auto descriptor = get(id);
5113 if (descriptor == nullptr) {
5114 return sp<BasicClient>{nullptr};
5115 }
5116 return descriptor->getValue();
5117}
5118
Austin Borgered99f642023-06-01 16:51:35 -07005119std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005120 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005121 std::ostringstream ret;
5122 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005123 bool hasAny = false;
5124 for (auto& i : all) {
5125 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005126 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005127 int32_t cost = i->getCost();
5128 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005129 int32_t score = i->getPriority().getScore();
5130 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005131 auto conflicting = i->getConflicting();
5132 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005133 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005134 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005135 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005136 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005137 uid_t clientUid = clientSp->getClientUid();
5138 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005139 }
Austin Borgered99f642023-06-01 16:51:35 -07005140 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5141 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005142
Ruben Brunk6267b532015-04-30 17:44:07 -07005143 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005144 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005145 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005146 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005147 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005148 }
5149
Austin Borgered99f642023-06-01 16:51:35 -07005150 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005151 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005152 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005153 }
Austin Borgered99f642023-06-01 16:51:35 -07005154 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005155 }
Austin Borgered99f642023-06-01 16:51:35 -07005156 if (hasAny) ret << "\n";
5157 ret << "]\n";
5158 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005159}
5160
5161CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005162 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5163 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005164 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005165
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005166 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005167 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005168
Austin Borgered99f642023-06-01 16:51:35 -07005169 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005170 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5171 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005172}
5173
5174CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005175 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005176 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005177 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005178 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005179 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5180 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005181}
5182
5183// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005184// InjectionStatusListener
5185// ----------------------------------------------------------------------------
5186
5187void CameraService::InjectionStatusListener::addListener(
5188 const sp<ICameraInjectionCallback>& callback) {
5189 Mutex::Autolock lock(mListenerLock);
5190 if (mCameraInjectionCallback) return;
5191 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5192 if (res == OK) {
5193 mCameraInjectionCallback = callback;
5194 }
5195}
5196
5197void CameraService::InjectionStatusListener::removeListener() {
5198 Mutex::Autolock lock(mListenerLock);
5199 if (mCameraInjectionCallback == nullptr) {
5200 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5201 return;
5202 }
5203 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5204 mCameraInjectionCallback = nullptr;
5205}
5206
5207void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005208 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005209 if (mCameraInjectionCallback == nullptr) {
5210 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5211 return;
5212 }
Cliff Wud3a05312021-04-26 23:07:31 +08005213
5214 switch (err) {
5215 case -ENODEV:
5216 mCameraInjectionCallback->onInjectionError(
5217 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5218 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005219 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005220 break;
5221 case -EBUSY:
5222 mCameraInjectionCallback->onInjectionError(
5223 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5224 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005225 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005226 break;
5227 case DEAD_OBJECT:
5228 mCameraInjectionCallback->onInjectionError(
5229 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5230 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005231 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005232 break;
5233 case INVALID_OPERATION:
5234 mCameraInjectionCallback->onInjectionError(
5235 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5236 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005237 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005238 break;
5239 case UNKNOWN_TRANSACTION:
5240 mCameraInjectionCallback->onInjectionError(
5241 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5242 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005243 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005244 break;
5245 default:
5246 mCameraInjectionCallback->onInjectionError(
5247 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5248 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005249 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005250 }
Cliff Wud8cae102021-03-11 01:37:42 +08005251}
5252
5253void CameraService::InjectionStatusListener::binderDied(
5254 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005255 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5256 auto parent = mParent.promote();
5257 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005258 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5259 if (clientDescriptor != nullptr) {
5260 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5261 baseClientPtr->stopInjection();
5262 }
Cliff Wu3b268182021-07-06 15:44:43 +08005263 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005264 }
5265}
5266
5267// ----------------------------------------------------------------------------
5268// CameraInjectionSession
5269// ----------------------------------------------------------------------------
5270
5271binder::Status CameraService::CameraInjectionSession::stopInjection() {
5272 Mutex::Autolock lock(mInjectionSessionLock);
5273 auto parent = mParent.promote();
5274 if (parent == nullptr) {
5275 ALOGE("CameraInjectionSession: Parent is gone");
5276 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5277 "Camera service encountered error");
5278 }
Cliff Wud3a05312021-04-26 23:07:31 +08005279
5280 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005281 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5282 if (clientDescriptor != nullptr) {
5283 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5284 res = baseClientPtr->stopInjection();
5285 if (res != OK) {
5286 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5287 " ret != NO_ERROR: %d", res);
5288 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5289 "Camera session encountered error");
5290 }
5291 }
Cliff Wu3b268182021-07-06 15:44:43 +08005292 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005293 return binder::Status::ok();
5294}
5295
5296// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297
5298static const int kDumpLockRetries = 50;
5299static const int kDumpLockSleep = 60000;
5300
5301static bool tryLock(Mutex& mutex)
5302{
5303 bool locked = false;
5304 for (int i = 0; i < kDumpLockRetries; ++i) {
5305 if (mutex.tryLock() == NO_ERROR) {
5306 locked = true;
5307 break;
5308 }
5309 usleep(kDumpLockSleep);
5310 }
5311 return locked;
5312}
5313
Rucha Katakwardf223072021-06-15 10:21:00 -07005314void CameraService::cacheDump() {
5315 if (mMemFd != -1) {
5316 const Vector<String16> args;
5317 ATRACE_CALL();
5318 // Acquiring service lock here will avoid the deadlock since
5319 // cacheDump will not be called during the second disconnect.
5320 Mutex::Autolock lock(mServiceLock);
5321
5322 Mutex::Autolock l(mCameraStatesLock);
5323 // Start collecting the info for open sessions and store it in temp file.
5324 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005325 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005326 auto clientDescriptor = mActiveClientManager.get(cameraId);
5327 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005328 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005329 // Log the current open session info before device is disconnected.
5330 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5331 }
5332 }
5333 }
5334}
5335
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005337 ATRACE_CALL();
5338
Austin Borgered99f642023-06-01 16:51:35 -07005339 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005340 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07005341 CameraThreadState::getCallingPid(),
5342 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005343 return NO_ERROR;
5344 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005345 bool locked = tryLock(mServiceLock);
5346 // failed to lock - CameraService is probably deadlocked
5347 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005348 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005349 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005350
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005351 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005352 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005353
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005354 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005355 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005356
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005357 if (locked) mServiceLock.unlock();
5358 return NO_ERROR;
5359 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005360 dprintf(fd, "\n== Service global info: ==\n\n");
5361 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005362 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005363 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5364 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005365 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5366 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5367 }
Austin Borgered99f642023-06-01 16:51:35 -07005368 std::string activeClientString = mActiveClientManager.toString();
5369 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5370 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005371 if (mStreamUseCaseOverrides.size() > 0) {
5372 dprintf(fd, "Active stream use case overrides:");
5373 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5374 dprintf(fd, " %" PRId64, useCaseOverride);
5375 }
5376 dprintf(fd, "\n");
5377 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005378
5379 dumpEventLog(fd);
5380
5381 bool stateLocked = tryLock(mCameraStatesLock);
5382 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005383 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005384 }
5385
Emilian Peevbd8c5032018-02-14 23:05:40 +00005386 int argSize = args.size();
5387 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005388 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005389 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005390 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005391 }
5392 break;
5393 }
5394 }
5395
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005396 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005397 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005398
Austin Borgered99f642023-06-01 16:51:35 -07005399 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005400
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005401 CameraParameters p = state.second->getShimParams();
5402 if (!p.isEmpty()) {
5403 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5404 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005405 }
5406
5407 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005408 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005409 // log the current open session info
5410 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005411 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005412 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005413 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005414
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005415 }
5416
5417 if (stateLocked) mCameraStatesLock.unlock();
5418
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005419 if (locked) mServiceLock.unlock();
5420
Emilian Peevf53f66e2017-04-11 14:29:43 +01005421 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005422
5423 dprintf(fd, "\n== Vendor tags: ==\n\n");
5424
5425 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5426 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005427 sp<VendorTagDescriptorCache> cache =
5428 VendorTagDescriptorCache::getGlobalVendorTagCache();
5429 if (cache == NULL) {
5430 dprintf(fd, "No vendor tags.\n");
5431 } else {
5432 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5433 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005434 } else {
5435 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5436 }
5437
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005438 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005439 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005440 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005441
5442 // Process dump arguments, if any
5443 int n = args.size();
5444 String16 verboseOption("-v");
5445 String16 unreachableOption("--unreachable");
5446 for (int i = 0; i < n; i++) {
5447 if (args[i] == verboseOption) {
5448 // change logging level
5449 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005450 std::string levelStr = toStdString(args[i+1]);
5451 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005452 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005453 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005454 } else if (args[i] == unreachableOption) {
5455 // Dump memory analysis
5456 // TODO - should limit be an argument parameter?
5457 UnreachableMemoryInfo info;
5458 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5459 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005460 dprintf(fd, "\n== Unable to dump unreachable memory. "
5461 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005462 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005463 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005464 std::string s = info.ToString(/*log_contents*/ true);
5465 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 }
5467 }
5468 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005469
5470 bool serviceLocked = tryLock(mServiceLock);
5471
5472 // Dump info from previous open sessions.
5473 // Reposition the offset to beginning of the file before reading
5474
5475 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5476 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5477 ssize_t size_read;
5478 char buf[4096];
5479 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5480 // Read data from file to a small buffer and write it to fd.
5481 write(fd, buf, size_read);
5482 if (size_read == -1) {
5483 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5484 break;
5485 }
5486 }
5487 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5488 } else {
5489 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5490 }
5491
5492 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 return NO_ERROR;
5494}
5495
Rucha Katakwardf223072021-06-15 10:21:00 -07005496void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005497 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005498 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005499 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005500 getFormattedCurrentTime().c_str(),
5501 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005502 dprintf(fd, " Client priority score: %d state: %d\n",
5503 clientDescriptor->getPriority().getScore(),
5504 clientDescriptor->getPriority().getState());
5505 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5506
5507 auto client = clientDescriptor->getValue();
5508 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005509 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005510
5511 client->dumpClient(fd, args);
5512}
5513
Austin Borgered99f642023-06-01 16:51:35 -07005514void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005515 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005516 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005517}
5518
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005519void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005520 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005521
5522 Mutex::Autolock l(mLogLock);
5523 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005524 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005525 }
5526
5527 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005528 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005529 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005530 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005531 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005532 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005533}
5534
Austin Borgered99f642023-06-01 16:51:35 -07005535void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005536 Mutex::Autolock lock(mLogLock);
5537 if (!isClientWatchedLocked(client)) { return; }
5538
5539 std::vector<std::string> dumpVector;
5540 client->dumpWatchedEventsToVector(dumpVector);
5541
5542 if (dumpVector.empty()) { return; }
5543
Austin Borgered99f642023-06-01 16:51:35 -07005544 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005545
Austin Borgered99f642023-06-01 16:51:35 -07005546 std::string currentTime = getFormattedCurrentTime();
5547 dumpString << "Cached @ ";
5548 dumpString << currentTime;
5549 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005550
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005551 size_t i = dumpVector.size();
5552
5553 // Store the string in reverse order (latest last)
5554 while (i > 0) {
5555 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005556 dumpString << cameraId;
5557 dumpString << ":";
5558 dumpString << client->getPackageName();
5559 dumpString << " ";
5560 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005561 }
5562
Austin Borgered99f642023-06-01 16:51:35 -07005563 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005564}
5565
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005566void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005567 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005568 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5569 if (mTorchClientMap[i] == who) {
5570 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005571 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005572 status_t res = mFlashlight->setTorchMode(cameraId, false);
5573 if (res) {
5574 ALOGE("%s: torch client died but couldn't turn off torch: "
5575 "%s (%d)", __FUNCTION__, strerror(-res), res);
5576 return;
5577 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005578 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005579 break;
5580 }
5581 }
5582}
5583
Ruben Brunkcc776712015-02-17 20:18:47 -08005584/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005585
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005586 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005587 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5588 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005589 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005590 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005591 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005592
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005593 // check torch client
5594 handleTorchClientBinderDied(who);
5595
5596 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005597 if(!evictClientIdByRemote(who)) {
5598 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005599 return;
5600 }
5601
Ruben Brunkcc776712015-02-17 20:18:47 -08005602 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5603 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005604}
5605
Austin Borgered99f642023-06-01 16:51:35 -07005606void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005607 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005608}
5609
Austin Borgered99f642023-06-01 16:51:35 -07005610void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005611 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005612 // Do not lock mServiceLock here or can get into a deadlock from
5613 // connect() -> disconnect -> updateStatus
5614
5615 auto state = getCameraState(cameraId);
5616
5617 if (state == nullptr) {
5618 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005619 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005620 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005621 }
5622
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005623 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5624 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5625 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005626 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005627 return;
5628 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005629
5630 // Collect the logical cameras without holding mStatusLock in updateStatus
5631 // as that can lead to a deadlock(b/162192331).
5632 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005633 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005634 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005635 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005636 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005637 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005638
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005639 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005640 // Update torch status if it has a flash unit.
5641 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005642 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005643 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5644 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005645 TorchModeStatus newTorchStatus =
5646 status == StatusInternal::PRESENT ?
5647 TorchModeStatus::AVAILABLE_OFF :
5648 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005649 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005650 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005651 }
5652 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005653 }
5654
5655 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005656 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005657 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005658
Ruben Brunkcc776712015-02-17 20:18:47 -08005659 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005660 bool isVendorListener = listener->isVendorListener();
5661 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
Kwangkyu Park01f84432023-09-15 17:08:17 +09005662 listener->getListenerPid(), listener->getListenerUid())) {
Shuzhen Wangb8259792021-05-27 09:27:06 -07005663 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005664 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005665 continue;
5666 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005667 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005668 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005669 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005670 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005671 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5672 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005673 // Also trigger the callbacks for cameras that were remapped to the current
5674 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005675 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005676 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5677 for (auto& remappedCameraId : remappedCameraIds) {
5678 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005679 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005680 listener->handleBinderStatus(ret,
5681 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5682 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5683 ret.exceptionCode());
5684 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005685 }
5686 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005687}
5688
Austin Borgered99f642023-06-01 16:51:35 -07005689void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5690 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005691 auto state = getCameraState(cameraId);
5692 if (state == nullptr) {
5693 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005694 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005695 return;
5696 }
5697 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005698 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005699 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005700 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005701 }
5702
Shuzhen Wang695044d2020-03-06 09:02:23 -08005703 Mutex::Autolock lock(mStatusListenerLock);
5704
5705 for (const auto& it : mListenerList) {
5706 if (!it->isOpenCloseCallbackAllowed()) {
5707 continue;
5708 }
5709
5710 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005711 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005712 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005713 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005714 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005715 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005716
5717 it->handleBinderStatus(ret,
5718 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5719 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005720 }
5721}
5722
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005723template<class Func>
5724void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005725 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005726 std::initializer_list<StatusInternal> rejectSourceStates,
5727 Func onStatusUpdatedLocked) {
5728 Mutex::Autolock lock(mStatusLock);
5729 StatusInternal oldStatus = mStatus;
5730 mStatus = status;
5731
5732 if (oldStatus == status) {
5733 return;
5734 }
5735
5736 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005737 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005738
5739 if (oldStatus == StatusInternal::NOT_PRESENT &&
5740 (status != StatusInternal::PRESENT &&
5741 status != StatusInternal::ENUMERATING)) {
5742
5743 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5744 __FUNCTION__);
5745 mStatus = oldStatus;
5746 return;
5747 }
5748
5749 /**
5750 * Sometimes we want to conditionally do a transition.
5751 * For example if a client disconnects, we want to go to PRESENT
5752 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5753 */
5754 for (auto& rejectStatus : rejectSourceStates) {
5755 if (oldStatus == rejectStatus) {
5756 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005757 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005758 mStatus = oldStatus;
5759 return;
5760 }
5761 }
5762
5763 onStatusUpdatedLocked(cameraId, status);
5764}
5765
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005766status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005767 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005768 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005769 if (!status) {
5770 return BAD_VALUE;
5771 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005772 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5773 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005774 // invalid camera ID or the camera doesn't have a flash unit
5775 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005776 }
5777
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005778 *status = mTorchStatusMap.valueAt(index);
5779 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005780}
5781
Austin Borgered99f642023-06-01 16:51:35 -07005782status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005783 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005784 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5785 if (index == NAME_NOT_FOUND) {
5786 return BAD_VALUE;
5787 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005788 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005789
5790 return OK;
5791}
5792
Austin Borgered99f642023-06-01 16:51:35 -07005793std::list<std::string> CameraService::getLogicalCameras(
5794 const std::string& physicalCameraId) {
5795 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005796 Mutex::Autolock lock(mCameraStatesLock);
5797 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005798 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5799 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005800 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005801 }
5802 return retList;
5803}
5804
5805void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005806 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005807 SystemCameraKind deviceKind) {
5808 // mStatusListenerLock is expected to be locked
5809 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005810 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005811 // Note: we check only the deviceKind of the physical camera id
5812 // since, logical camera ids and their physical camera ids are
5813 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005814 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5815 listener->getListenerPid(), listener->getListenerUid())) {
5816 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005817 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005818 continue;
5819 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005820 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005821 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005822 listener->handleBinderStatus(ret,
5823 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5824 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5825 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005826 }
5827 }
5828}
5829
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005830
Svet Ganova453d0d2018-01-11 15:37:58 -08005831void CameraService::blockClientsForUid(uid_t uid) {
5832 const auto clients = mActiveClientManager.getAll();
5833 for (auto& current : clients) {
5834 if (current != nullptr) {
5835 const auto basicClient = current->getValue();
5836 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5837 basicClient->block();
5838 }
5839 }
5840 }
5841}
5842
Michael Grooverd1d435a2018-12-18 17:39:42 -08005843void CameraService::blockAllClients() {
5844 const auto clients = mActiveClientManager.getAll();
5845 for (auto& current : clients) {
5846 if (current != nullptr) {
5847 const auto basicClient = current->getValue();
5848 if (basicClient.get() != nullptr) {
5849 basicClient->block();
5850 }
5851 }
5852 }
5853}
5854
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005855void CameraService::blockPrivacyEnabledClients() {
5856 const auto clients = mActiveClientManager.getAll();
5857 for (auto& current : clients) {
5858 if (current != nullptr) {
5859 const auto basicClient = current->getValue();
5860 if (basicClient.get() != nullptr) {
5861 std::string pkgName = basicClient->getPackageName();
5862 bool cameraPrivacyEnabled =
5863 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5864 if (cameraPrivacyEnabled) {
5865 basicClient->block();
5866 }
5867 }
5868 }
5869 }
5870}
5871
Svet Ganova453d0d2018-01-11 15:37:58 -08005872// NOTE: This is a remote API - make sure all args are validated
5873status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005874 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005875 return PERMISSION_DENIED;
5876 }
5877 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5878 return BAD_VALUE;
5879 }
Austin Borgered99f642023-06-01 16:51:35 -07005880 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005881 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005882 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005883 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005884 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005885 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005886 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005887 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005888 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005889 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005890 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005891 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005892 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005893 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005894 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005895 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005896 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005897 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005898 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005899 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005900 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005901 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005902 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005903 handleClearStreamUseCaseOverrides();
5904 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005905 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005906 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005907 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005908 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005909 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005910 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005911 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005912 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005913 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005914 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005915 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005916 }
5917 printHelp(err);
5918 return BAD_VALUE;
5919}
5920
malikakash82ed4352023-07-21 22:44:34 +00005921status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5922 uid_t uid = IPCThreadState::self()->getCallingUid();
5923 if (uid != AID_ROOT) {
5924 dprintf(err, "Must be adb root\n");
5925 return PERMISSION_DENIED;
5926 }
5927 if (args.size() != 4) {
5928 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5929 return BAD_VALUE;
5930 }
Austin Borgered99f642023-06-01 16:51:35 -07005931 std::string packageName = toStdString(args[1]);
5932 std::string cameraIdToReplace = toStdString(args[2]);
5933 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005934 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5935 return OK;
5936}
5937
Svet Ganova453d0d2018-01-11 15:37:58 -08005938status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005939 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005940
Svet Ganova453d0d2018-01-11 15:37:58 -08005941 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005942 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005943 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005944 } else if ((args[2] != toString16("idle"))) {
5945 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005946 return BAD_VALUE;
5947 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005948
5949 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005950 if (args.size() >= 5 && args[3] == toString16("--user")) {
5951 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005952 }
5953
5954 uid_t uid;
5955 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5956 return BAD_VALUE;
5957 }
5958
5959 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005960 return NO_ERROR;
5961}
5962
5963status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005964 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005965
5966 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005967 if (args.size() >= 4 && args[2] == toString16("--user")) {
5968 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005969 }
5970
5971 uid_t uid;
5972 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005973 return BAD_VALUE;
5974 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005975
5976 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005977 return NO_ERROR;
5978}
5979
5980status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005981 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005982
5983 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005984 if (args.size() >= 4 && args[2] == toString16("--user")) {
5985 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005986 }
5987
5988 uid_t uid;
5989 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005990 return BAD_VALUE;
5991 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005992
5993 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005994 return dprintf(out, "active\n");
5995 } else {
5996 return dprintf(out, "idle\n");
5997 }
5998}
5999
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006000status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006001 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006002 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6003 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6004 Mutex::Autolock lock(mServiceLock);
6005
6006 mOverrideRotateAndCropMode = rotateValue;
6007
6008 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6009
6010 const auto clients = mActiveClientManager.getAll();
6011 for (auto& current : clients) {
6012 if (current != nullptr) {
6013 const auto basicClient = current->getValue();
6014 if (basicClient.get() != nullptr) {
6015 basicClient->setRotateAndCropOverride(rotateValue);
6016 }
6017 }
6018 }
6019
6020 return OK;
6021}
6022
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006023status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6024 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006025 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006026 if ((*end != '\0') ||
6027 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6028 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6029 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6030 return BAD_VALUE;
6031 }
6032
6033 Mutex::Autolock lock(mServiceLock);
6034 mOverrideAutoframingMode = autoframingValue;
6035
6036 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6037
6038 const auto clients = mActiveClientManager.getAll();
6039 for (auto& current : clients) {
6040 if (current != nullptr) {
6041 const auto basicClient = current->getValue();
6042 if (basicClient.get() != nullptr) {
6043 basicClient->setAutoframingOverride(autoframingValue);
6044 }
6045 }
6046 }
6047
6048 return OK;
6049}
6050
Ravneetaeb20dc2022-03-30 05:33:03 +00006051status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006052 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006053
6054 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6055
6056 Mutex::Autolock lock(mServiceLock);
6057
6058 mCameraServiceWatchdogEnabled = enableWatchdog;
6059
6060 const auto clients = mActiveClientManager.getAll();
6061 for (auto& current : clients) {
6062 if (current != nullptr) {
6063 const auto basicClient = current->getValue();
6064 if (basicClient.get() != nullptr) {
6065 basicClient->setCameraServiceWatchdog(enableWatchdog);
6066 }
6067 }
6068 }
6069
6070 return OK;
6071}
6072
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006073status_t CameraService::handleGetRotateAndCrop(int out) {
6074 Mutex::Autolock lock(mServiceLock);
6075
6076 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6077}
6078
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006079status_t CameraService::handleGetAutoframing(int out) {
6080 Mutex::Autolock lock(mServiceLock);
6081
6082 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6083}
6084
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006085status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6086 char *endPtr;
6087 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006088 std::string maskString = toStdString(args[1]);
6089 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006090
6091 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006092 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006093 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6094
6095 Mutex::Autolock lock(mServiceLock);
6096
6097 mImageDumpMask = maskValue;
6098
6099 return OK;
6100}
6101
6102status_t CameraService::handleGetImageDumpMask(int out) {
6103 Mutex::Autolock lock(mServiceLock);
6104
6105 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6106}
6107
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006108status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006109 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006110 if (errno != 0) return BAD_VALUE;
6111
6112 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6113 Mutex::Autolock lock(mServiceLock);
6114
6115 mOverrideCameraMuteMode = (muteValue == 1);
6116
6117 const auto clients = mActiveClientManager.getAll();
6118 for (auto& current : clients) {
6119 if (current != nullptr) {
6120 const auto basicClient = current->getValue();
6121 if (basicClient.get() != nullptr) {
6122 if (basicClient->supportsCameraMute()) {
6123 basicClient->setCameraMute(mOverrideCameraMuteMode);
6124 }
6125 }
6126 }
6127 }
6128
6129 return OK;
6130}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006131
Shuzhen Wang16610a62022-12-15 22:38:07 -08006132status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6133 std::vector<int64_t> useCasesOverride;
6134 for (size_t i = 1; i < args.size(); i++) {
6135 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006136 std::string arg = toStdString(args[i]);
6137 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006138 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006139 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006140 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006141 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006142 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006143 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006144 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006145 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006146 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006147 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006148 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006149 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006150 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6151 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006152 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006153 return BAD_VALUE;
6154 }
6155 useCasesOverride.push_back(useCase);
6156 }
6157
6158 Mutex::Autolock lock(mServiceLock);
6159 mStreamUseCaseOverrides = std::move(useCasesOverride);
6160
6161 return OK;
6162}
6163
6164void CameraService::handleClearStreamUseCaseOverrides() {
6165 Mutex::Autolock lock(mServiceLock);
6166 mStreamUseCaseOverrides.clear();
6167}
6168
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006169status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6170 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006171 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006172 if ((*end != '\0') ||
6173 (zoomOverrideValue != -1 &&
6174 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6175 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6176 return BAD_VALUE;
6177 }
6178
6179 Mutex::Autolock lock(mServiceLock);
6180 mZoomOverrideValue = zoomOverrideValue;
6181
6182 const auto clients = mActiveClientManager.getAll();
6183 for (auto& current : clients) {
6184 if (current != nullptr) {
6185 const auto basicClient = current->getValue();
6186 if (basicClient.get() != nullptr) {
6187 if (basicClient->supportsZoomOverride()) {
6188 basicClient->setZoomOverride(mZoomOverrideValue);
6189 }
6190 }
6191 }
6192 }
6193
6194 return OK;
6195}
6196
Avichal Rakesh84147132021-11-11 17:47:11 -08006197status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006198 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006199 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006200 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006201 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006202 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006203 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006204 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006205 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006206 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006207 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006208 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006209 dprintf(outFd, "Camera service watch commands:\n"
6210 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6211 " starts watching the provided tags for clients with provided package\n"
6212 " recognizes tag shorthands like '3a'\n"
6213 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006214 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006215 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006216 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006217 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006218 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006219 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006220 return BAD_VALUE;
6221}
6222
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006223status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6224 Mutex::Autolock lock(mLogLock);
6225 size_t tagsIdx; // index of '-m'
6226 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006227 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006228 if (tagsIdx < args.size() - 1) {
6229 tags = args[tagsIdx + 1];
6230 } else {
6231 dprintf(outFd, "No tags provided.\n");
6232 return BAD_VALUE;
6233 }
6234
6235 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006236 // watch all clients if no clients are provided
6237 String16 clients = toString16(kWatchAllClientsFlag);
6238 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006239 clientsIdx++);
6240 if (clientsIdx < args.size() - 1) {
6241 clients = args[clientsIdx + 1];
6242 }
Austin Borgered99f642023-06-01 16:51:35 -07006243 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006244
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006245 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006246 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006247
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006248 bool serviceLock = tryLock(mServiceLock);
6249 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006250 auto cameraClients = mActiveClientManager.getAll();
6251 for (const auto &clientDescriptor: cameraClients) {
6252 if (clientDescriptor == nullptr) { continue; }
6253 sp<BasicClient> client = clientDescriptor->getValue();
6254 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006255
6256 if (isClientWatchedLocked(client.get())) {
6257 client->startWatchingTags(mMonitorTags, outFd);
6258 numWatchedClients++;
6259 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006260 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006261 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6262
6263 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006264 return OK;
6265}
6266
6267status_t CameraService::stopWatchingTags(int outFd) {
6268 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006269 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006270 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006271
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006272 mWatchedClientPackages.clear();
6273 mWatchedClientsDumpCache.clear();
6274
6275 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006276 auto cameraClients = mActiveClientManager.getAll();
6277 for (const auto &clientDescriptor : cameraClients) {
6278 if (clientDescriptor == nullptr) { continue; }
6279 sp<BasicClient> client = clientDescriptor->getValue();
6280 if (client.get() == nullptr) { continue; }
6281 client->stopWatchingTags(outFd);
6282 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006283 dprintf(outFd, "Stopped watching all clients.\n");
6284 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006285 return OK;
6286}
6287
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006288status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6289 Mutex::Autolock lock(mLogLock);
6290 size_t clearedSize = mWatchedClientsDumpCache.size();
6291 mWatchedClientsDumpCache.clear();
6292 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6293 return OK;
6294}
6295
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006296status_t CameraService::printWatchedTags(int outFd) {
6297 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006298 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006299
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006300 bool printedSomething = false; // tracks if any monitoring information was printed
6301 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006302
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006303 bool serviceLock = tryLock(mServiceLock);
6304 // get all watched clients that are currently connected
6305 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6306 if (clientDescriptor == nullptr) { continue; }
6307
6308 sp<BasicClient> client = clientDescriptor->getValue();
6309 if (client.get() == nullptr) { continue; }
6310 if (!isClientWatchedLocked(client.get())) { continue; }
6311
6312 std::vector<std::string> dumpVector;
6313 client->dumpWatchedEventsToVector(dumpVector);
6314
6315 size_t printIdx = dumpVector.size();
6316 if (printIdx == 0) {
6317 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006318 }
6319
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006320 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006321 const std::string &cameraId = clientDescriptor->getKey();
6322 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006323 while(printIdx > 0) {
6324 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006325 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006326 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006327 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006328 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006329 printedSomething = true;
6330
6331 connectedMonitoredClients.emplace(client->getPackageName());
6332 }
6333 if (serviceLock) { mServiceLock.unlock(); }
6334
6335 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6336 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006337 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006338 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6339 continue;
6340 }
6341
Austin Borgered99f642023-06-01 16:51:35 -07006342 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006343 dprintf(outFd, "%s\n", kv.second.c_str());
6344 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006345 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006346
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006347 if (!printedSomething) {
6348 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006349 }
6350
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006351 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006352}
6353
Avichal Rakesh84147132021-11-11 17:47:11 -08006354// Print all events in vector `events' that came after lastPrintedEvent
6355void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006356 const std::string &cameraId,
6357 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006358 const std::vector<std::string> &events,
6359 const std::string &lastPrintedEvent) {
6360 if (events.empty()) { return; }
6361
6362 // index of lastPrintedEvent in events.
6363 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6364 size_t lastPrintedIdx;
6365 for (lastPrintedIdx = 0;
6366 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6367 lastPrintedIdx++);
6368
6369 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6370
Avichal Rakesh84147132021-11-11 17:47:11 -08006371 // print events in chronological order (latest event last)
6372 size_t idxToPrint = lastPrintedIdx;
6373 do {
6374 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006375 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6376 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006377 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006378}
6379
6380// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6381// command should be interrupted if the user presses the return key, or if user loses any way to
6382// signal interrupt.
6383// If timeoutMs == 0, this function will always return false
6384bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6385 struct timeval startTime;
6386 int startTimeError = gettimeofday(&startTime, nullptr);
6387 if (startTimeError) {
6388 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6389 return true;
6390 }
6391
6392 const nfds_t numFds = 1;
6393 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6394
6395 struct timeval currTime;
6396 char buffer[2];
6397 while(true) {
6398 int currTimeError = gettimeofday(&currTime, nullptr);
6399 if (currTimeError) {
6400 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6401 return true;
6402 }
6403
6404 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6405 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6406 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6407
6408 if (remainingTimeMs <= 0) {
6409 // No user interrupt within timeoutMs, don't interrupt watch command
6410 return false;
6411 }
6412
6413 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6414 if (numFdsUpdated < 0) {
6415 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6416 return true;
6417 }
6418
6419 if (numFdsUpdated == 0) {
6420 // No user input within timeoutMs, don't interrupt watch command
6421 return false;
6422 }
6423
6424 if (!(pollFd.revents & POLLIN)) {
6425 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6426 return true;
6427 }
6428
6429 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6430 if (sizeRead < 0) {
6431 dprintf(outFd, "Error reading user input. Exiting.\n");
6432 return true;
6433 }
6434
6435 if (sizeRead == 0) {
6436 // Reached end of input fd (can happen if input is piped)
6437 // User has no way to signal an interrupt, so interrupt here
6438 return true;
6439 }
6440
6441 if (buffer[0] == '\n') {
6442 // User pressed return, interrupt watch command.
6443 return true;
6444 }
6445 }
6446}
6447
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006448status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6449 int inFd, int outFd) {
6450 // Figure out refresh interval, if present in args
6451 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006452 if (args.size() > 2) {
6453 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006454 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006455 intervalIdx++);
6456
6457 size_t intervalValIdx = intervalIdx + 1;
6458 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006459 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006460 if (errno) { return BAD_VALUE; }
6461 }
6462 }
6463
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006464 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6465 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006466
Avichal Rakesh84147132021-11-11 17:47:11 -08006467 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006468 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006469
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006470 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006471 bool serviceLock = tryLock(mServiceLock);
6472 auto cameraClients = mActiveClientManager.getAll();
6473 if (serviceLock) { mServiceLock.unlock(); }
6474
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006475 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006476 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006477 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006478
6479 sp<BasicClient> client = clientDescriptor->getValue();
6480 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006481 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006482
Austin Borgered99f642023-06-01 16:51:35 -07006483 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006484 // This also initializes the map entries with an empty string
6485 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6486
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006487 std::vector<std::string> latestEvents;
6488 client->dumpWatchedEventsToVector(latestEvents);
6489
6490 if (!latestEvents.empty()) {
6491 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006492 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006493 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006494 latestEvents,
6495 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006496 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006497 }
6498 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006499 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006500 break;
6501 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006502 }
6503 return OK;
6504}
6505
Austin Borgered99f642023-06-01 16:51:35 -07006506void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006507 mWatchedClientPackages.clear();
6508
Austin Borgered99f642023-06-01 16:51:35 -07006509 std::istringstream iss(clients);
6510 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006511
Austin Borgered99f642023-06-01 16:51:35 -07006512 while (std::getline(iss, nextClient, ',')) {
6513 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006514 // Don't need to track any other package if 'all' is present
6515 mWatchedClientPackages.clear();
6516 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6517 break;
6518 }
6519
6520 // track package names
6521 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006522 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006523}
6524
Svet Ganova453d0d2018-01-11 15:37:58 -08006525status_t CameraService::printHelp(int out) {
6526 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006527 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6528 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6529 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006530 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6531 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6532 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006533 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6534 " Valid values 0=false, 1=true, 2=auto\n"
6535 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006536 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6537 " Valid values 0=OFF, 1=ON for JPEG\n"
6538 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006539 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006540 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6541 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6542 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6543 " on. In case the number of usecases is smaller than the number of streams, the\n"
6544 " last use case is assigned to all the remaining streams. In case of multiple\n"
6545 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6546 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6547 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6548 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006549 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6550 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006551 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6552 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006553 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006554 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006555 " help print this message\n");
6556}
6557
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006558bool CameraService::isClientWatched(const BasicClient *client) {
6559 Mutex::Autolock lock(mLogLock);
6560 return isClientWatchedLocked(client);
6561}
6562
6563bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6564 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6565 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6566}
6567
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006568int32_t CameraService::updateAudioRestriction() {
6569 Mutex::Autolock lock(mServiceLock);
6570 return updateAudioRestrictionLocked();
6571}
6572
6573int32_t CameraService::updateAudioRestrictionLocked() {
6574 int32_t mode = 0;
6575 // iterate through all active client
6576 for (const auto& i : mActiveClientManager.getAll()) {
6577 const auto clientSp = i->getValue();
6578 mode |= clientSp->getAudioRestriction();
6579 }
6580
6581 bool modeChanged = (mAudioRestriction != mode);
6582 mAudioRestriction = mode;
6583 if (modeChanged) {
6584 mAppOps.setCameraAudioRestriction(mode);
6585 }
6586 return mode;
6587}
6588
Austin Borgered99f642023-06-01 16:51:35 -07006589status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006590 sp<BasicClient> clientSp) {
6591 std::unique_ptr<AutoConditionLock> lock =
6592 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6593 status_t res = NO_ERROR;
6594 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006595 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006596 mInjectionStatusListener->notifyInjectionError(
6597 externalCamId, UNKNOWN_TRANSACTION);
6598 clientSp->notifyError(
6599 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6600 CaptureResultExtras());
6601
6602 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6603 // other clients from connecting in mServiceLockWrapper if held
6604 mServiceLock.unlock();
6605
6606 // Clear caller identity temporarily so client disconnect PID checks work correctly
6607 int64_t token = CameraThreadState::clearCallingIdentity();
6608 clientSp->disconnect();
6609 CameraThreadState::restoreCallingIdentity(token);
6610
6611 // Reacquire mServiceLock
6612 mServiceLock.lock();
6613 }
6614
6615 return res;
6616}
6617
Cliff Wud3a05312021-04-26 23:07:31 +08006618void CameraService::clearInjectionParameters() {
6619 {
6620 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006621 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006622 mInjectionInternalCamId = "";
6623 }
6624 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006625 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006626}
6627
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628}; // namespace android