blob: 271cfec80514f65937157e48117db43c4debc95e [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>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Alex Deymo9c2a2c22016-08-25 11:59:14 -070036#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080037#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070038#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080039#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080040#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/MemoryBase.h>
43#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000060#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <utils/Errors.h>
62#include <utils/Log.h>
63#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070064#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080065#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080066#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080067#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080070
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070079#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070080
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080081namespace {
82 const char* kPermissionServiceName = "permission";
83}; // namespace anonymous
84
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070087using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080088using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000089using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070090using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080091using hardware::ICamera;
92using hardware::ICameraClient;
93using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +080094using hardware::camera2::ICameraInjectionCallback;
95using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080096using hardware::camera2::utils::CameraIdAndSessionConfiguration;
97using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080098
Mathias Agopian65ab4712010-07-14 17:59:35 -070099// ----------------------------------------------------------------------------
100// Logging support -- this is for debugging only
101// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700102volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
Steve Blockb8a80522011-12-20 16:23:08 +0000104#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
105#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106
107static void setLogLevel(int level) {
108 android_atomic_write(level, &gLogLevel);
109}
110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800111// Convenience methods for constructing binder::Status objects for error returns
112
113#define STATUS_ERROR(errorCode, errorString) \
114 binder::Status::fromServiceSpecificError(errorCode, \
115 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
116
117#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
118 binder::Status::fromServiceSpecificError(errorCode, \
119 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
120 __VA_ARGS__))
121
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122// ----------------------------------------------------------------------------
123
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700124static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800125static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sCameraPermission("android.permission.CAMERA");
127static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
128static const String16
129 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800130static const String16 sCameraOpenCloseListenerPermission(
131 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800132static const String16
133 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700134const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800135static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
136static constexpr int32_t kSystemNativeClientState =
137 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700138
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800139const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700140const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700141
Rucha Katakward9ea6452021-05-06 11:57:16 -0700142// Set to keep track of logged service error events.
143static std::set<String8> sServiceErrorEventSet;
144
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800145CameraService::CameraService() :
146 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800147 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700148 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700149 mSoundRef(0), mInitialized(false),
150 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000151 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800152 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700153 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
154 if (mMemFd == -1) {
155 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157}
158
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800159// The word 'System' here does not refer to clients only on the system
160// partition. They just need to have a android system uid.
161static bool doesClientHaveSystemUid() {
162 return (CameraThreadState::getCallingUid() < AID_APP_START);
163}
164
Iliyan Malchev8951a972011-04-14 16:55:59 -0700165void CameraService::onFirstRef()
166{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700167
Ruben Brunkcc776712015-02-17 20:18:47 -0800168 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800169
Iliyan Malchev8951a972011-04-14 16:55:59 -0700170 BnCameraService::onFirstRef();
171
Ruben Brunk99e69712015-05-26 17:25:07 -0700172 // Update battery life tracking if service is restarting
173 BatteryNotifier& notifier(BatteryNotifier::getInstance());
174 notifier.noteResetCamera();
175 notifier.noteResetFlashlight();
176
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800177 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800178
Emilian Peevf53f66e2017-04-11 14:29:43 +0100179 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800180 if (res == OK) {
181 mInitialized = true;
182 }
183
Svet Ganova453d0d2018-01-11 15:37:58 -0800184 mUidPolicy = new UidPolicy(this);
185 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800186 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
187 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800188 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700189 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700190 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
191 if (hcs->registerAsService() != android::OK) {
192 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
193 __FUNCTION__);
194 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700195
196 // This needs to be last call in this function, so that it's as close to
197 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700198 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700199 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800200}
201
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800202status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100204
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800205 std::vector<std::string> deviceIds;
206 {
207 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800208
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800209 if (nullptr == mCameraProviderManager.get()) {
210 mCameraProviderManager = new CameraProviderManager();
211 res = mCameraProviderManager->initialize(this);
212 if (res != OK) {
213 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
214 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700215 logServiceError(String8::format("Unable to initialize camera provider manager"),
216 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800217 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100218 }
219 }
220
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800221
222 // Setup vendor tags before we call get_camera_info the first time
223 // because HAL might need to setup static vendor keys in get_camera_info
224 // TODO: maybe put this into CameraProviderManager::initialize()?
225 mCameraProviderManager->setUpVendorTags();
226
227 if (nullptr == mFlashlight.get()) {
228 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700229 }
230
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800231 res = mFlashlight->findFlashUnits();
232 if (res != OK) {
233 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
234 }
235
236 deviceIds = mCameraProviderManager->getCameraDeviceIds();
237 }
238
239
240 for (auto& cameraId : deviceIds) {
241 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800242 if (getCameraState(id8) == nullptr) {
243 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
244 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800245 }
246
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700247 // Derive primary rear/front cameras, and filter their charactierstics.
248 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700249 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700250 // Assume internal cameras are advertised from the same
251 // provider. If multiple providers are registered at different time,
252 // and each provider contains multiple internal color cameras, the current
253 // logic may filter the characteristics of more than one front/rear color
254 // cameras.
255 Mutex::Autolock l(mServiceLock);
256 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700257 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700258
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800259 return OK;
260}
261
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700262void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
263 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800264 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800265 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700266 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
267 i->getListenerUid())) {
268 ALOGV("Skipping torch callback for system-only camera device %s",
269 cameraId.c_str());
270 continue;
271 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700272 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800273 }
274}
275
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800277 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800278 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800279 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800280 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281}
282
Emilian Peevaee727d2017-05-04 16:35:48 +0100283void CameraService::onNewProviderRegistered() {
284 enumerateProviders();
285}
286
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700287void CameraService::filterAPI1SystemCameraLocked(
288 const std::vector<std::string> &normalDeviceIds) {
289 mNormalDeviceIdsWithoutSystemCamera.clear();
290 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700291 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
292 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
293 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
294 continue;
295 }
296 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700297 // All system camera ids will necessarily come after public camera
298 // device ids as per the HAL interface contract.
299 break;
300 }
301 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
302 }
303 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
304 mNormalDeviceIdsWithoutSystemCamera.size());
305}
306
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700307status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
308 auto state = getCameraState(cameraId);
309 if (state != nullptr) {
310 *kind = state->getSystemCameraKind();
311 return OK;
312 }
313 // Hidden physical camera ids won't have CameraState
314 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
315}
316
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800317void CameraService::updateCameraNumAndIds() {
318 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700319 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
320 // Excludes hidden secure cameras
321 mNumberOfCameras =
322 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
323 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800324 mNormalDeviceIds =
325 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700326 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800327}
328
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700329void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700330 // To claim to be S Performance primary cameras, the cameras must be
331 // backward compatible. So performance class primary camera Ids must be API1
332 // compatible.
333 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
334 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
335 int facing = -1;
336 int orientation = 0;
337 String8 cameraId8(cameraId.c_str());
338 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
339 if (facing == -1) {
340 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
341 return;
342 }
343
344 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
345 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700346 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
347 if (res == OK) {
348 mPerfClassPrimaryCameraIds.insert(cameraId);
349 } else {
350 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
351 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
352 break;
353 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700354
355 if (facing == hardware::CAMERA_FACING_BACK) {
356 firstRearCameraSeen = true;
357 }
358 if (facing == hardware::CAMERA_FACING_FRONT) {
359 firstFrontCameraSeen = true;
360 }
361 }
362
363 if (firstRearCameraSeen && firstFrontCameraSeen) {
364 break;
365 }
366 }
367}
368
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100369void CameraService::addStates(const String8 id) {
370 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700371 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100372 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
373 if (res != OK) {
374 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
375 return;
376 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000377 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700378 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
379 if (res != OK) {
380 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
381 return;
382 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000383 std::vector<std::string> physicalCameraIds;
384 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100385 std::set<String8> conflicting;
386 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
387 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
388 }
389
390 {
391 Mutex::Autolock lock(mCameraStatesLock);
392 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000393 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100394 }
395
396 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100397 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100398 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800399
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700400 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100401 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800402
403 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100404 logDeviceAdded(id, "Device added");
405}
406
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100407void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800408 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100409 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100410 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100411 mTorchStatusMap.removeItem(id);
412 }
413
414 {
415 Mutex::Autolock lock(mCameraStatesLock);
416 mCameraStates.erase(id);
417 }
418}
419
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800420void CameraService::onDeviceStatusChanged(const String8& id,
421 CameraDeviceStatus newHalStatus) {
422 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
423 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700424
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800425 StatusInternal newStatus = mapToInternal(newHalStatus);
426
Ruben Brunkcc776712015-02-17 20:18:47 -0800427 std::shared_ptr<CameraState> state = getCameraState(id);
428
429 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700430 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100431 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700432 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100433
434 // First add as absent to make sure clients are notified below
435 addStates(id);
436
437 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700438 } else {
439 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
440 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700441 return;
442 }
443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800444 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800445
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800446 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800447 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700448 return;
449 }
450
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800451 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700452 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
453 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800454
455 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
456 // to this device until the status changes
457 updateStatus(StatusInternal::NOT_PRESENT, id);
458
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800459 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700460 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800461 // Don't do this in updateStatus to avoid deadlock over mServiceLock
462 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700463
Ruben Brunkcc776712015-02-17 20:18:47 -0800464 // Remove cached shim parameters
465 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700466
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800467 // Remove online as well as offline client from the list of active clients,
468 // if they are present
469 clientToDisconnectOnline = removeClientLocked(id);
470 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700471 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800472
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800473 disconnectClient(id, clientToDisconnectOnline);
474 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700475
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100476 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800477 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800478 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700479 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
480 newStatus));
481 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800482 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700483 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800484}
Igor Murashkincba2c162013-03-20 15:56:31 -0700485
Shuzhen Wang43858162020-01-10 13:42:15 -0800486void CameraService::onDeviceStatusChanged(const String8& id,
487 const String8& physicalId,
488 CameraDeviceStatus newHalStatus) {
489 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
490 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
491
492 StatusInternal newStatus = mapToInternal(newHalStatus);
493
494 std::shared_ptr<CameraState> state = getCameraState(id);
495
496 if (state == nullptr) {
497 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
498 __FUNCTION__, id.string(), physicalId.string());
499 return;
500 }
501
502 StatusInternal logicalCameraStatus = state->getStatus();
503 if (logicalCameraStatus != StatusInternal::PRESENT &&
504 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
505 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
506 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
507 return;
508 }
509
510 bool updated = false;
511 if (newStatus == StatusInternal::PRESENT) {
512 updated = state->removeUnavailablePhysicalId(physicalId);
513 } else {
514 updated = state->addUnavailablePhysicalId(physicalId);
515 }
516
517 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800518 String8 idCombo = id + " : " + physicalId;
519 if (newStatus == StatusInternal::PRESENT) {
520 logDeviceAdded(idCombo,
521 String8::format("Device status changed to %d", newStatus));
522 } else {
523 logDeviceRemoved(idCombo,
524 String8::format("Device status changed to %d", newStatus));
525 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700526 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
527 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
528 if (getSystemCameraKind(id, &deviceKind) != OK) {
529 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
530 return;
531 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800532 String16 id16(id), physicalId16(physicalId);
533 Mutex::Autolock lock(mStatusListenerLock);
534 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700535 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
536 listener->getListenerPid(), listener->getListenerUid())) {
537 ALOGV("Skipping discovery callback for system-only camera device %s",
538 id.c_str());
539 continue;
540 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800541 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
542 id16, physicalId16);
543 }
544 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700545}
546
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800547void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
548 if (clientToDisconnect.get() != nullptr) {
549 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
550 __FUNCTION__, id.string());
551 // Notify the client of disconnection
552 clientToDisconnect->notifyError(
553 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
554 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800555 clientToDisconnect->disconnect();
556 }
557}
558
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800559void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800560 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700561 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
562 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
563 if (res != OK) {
564 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
565 cameraId.string());
566 return;
567 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800568 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700569 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800570}
571
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700572
573void CameraService::onTorchStatusChanged(const String8& cameraId,
574 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
575 Mutex::Autolock al(mTorchStatusMutex);
576 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
577}
578
Rucha Katakwar38284522021-11-10 11:25:21 -0800579void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
580 int32_t newStrengthLevel) {
581 Mutex::Autolock lock(mStatusListenerLock);
582 for (auto& i : mListenerList) {
583 i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
584 newStrengthLevel);
585 }
586}
587
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800588void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700589 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800590 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
591 __FUNCTION__, cameraId.string(), newStatus);
592
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800593 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800594 status_t res = getTorchStatusLocked(cameraId, &status);
595 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700596 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
597 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800598 return;
599 }
600 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800601 return;
602 }
603
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800604 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800605 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800606 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
607 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800608 return;
609 }
610
Ruben Brunkcc776712015-02-17 20:18:47 -0800611 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700612 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700613 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700614 auto iter = mTorchUidMap.find(cameraId);
615 if (iter != mTorchUidMap.end()) {
616 int oldUid = iter->second.second;
617 int newUid = iter->second.first;
618 BatteryNotifier& notifier(BatteryNotifier::getInstance());
619 if (oldUid != newUid) {
620 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800621 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700622 notifier.noteFlashlightOff(cameraId, oldUid);
623 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800624 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700625 notifier.noteFlashlightOn(cameraId, newUid);
626 }
627 iter->second.second = newUid;
628 } else {
629 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800630 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700631 notifier.noteFlashlightOn(cameraId, oldUid);
632 } else {
633 notifier.noteFlashlightOff(cameraId, oldUid);
634 }
635 }
636 }
637 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700638 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800639}
640
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000641static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
642 bool logPermissionFailure = false) {
643 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
644 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700645 checkPermission(sCameraPermission, callingPid, callingUid);
646}
647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800648Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700649 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100650 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700651 bool hasSystemCameraPermissions =
652 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
653 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700654 switch (type) {
655 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700656 if (hasSystemCameraPermissions) {
657 *numCameras = static_cast<int>(mNormalDeviceIds.size());
658 } else {
659 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
660 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800661 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700662 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700663 if (hasSystemCameraPermissions) {
664 *numCameras = mNumberOfCameras;
665 } else {
666 *numCameras = mNumberOfCamerasWithoutSystemCamera;
667 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700669 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800670 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700671 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800672 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
673 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700674 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800675 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676}
677
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800678Status CameraService::getCameraInfo(int cameraId,
679 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700680 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100681 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700682 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
683 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
684 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
685 "characteristics for system only device %s: ", cameraIdStr.c_str());
686 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100687
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800688 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700689 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800690 return STATUS_ERROR(ERROR_DISCONNECTED,
691 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700692 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700693 bool hasSystemCameraPermissions =
694 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
695 CameraThreadState::getCallingUid());
696 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
697 if (hasSystemCameraPermissions) {
698 cameraIdBound = mNumberOfCameras;
699 }
700 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800701 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
702 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 }
704
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800705 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800706 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700707 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100708 if (err != OK) {
709 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
710 "Error retrieving camera info from device %d: %s (%d)", cameraId,
711 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700712 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
713 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800714 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100715
Ruben Brunkcc776712015-02-17 20:18:47 -0800716 return ret;
717}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700718
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800719std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700720 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
721 auto callingPid = CameraThreadState::getCallingPid();
722 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000723 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
724 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700725 deviceIds = &mNormalDeviceIds;
726 }
727 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800728 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700729 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800730 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800731 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800732
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700733 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800734}
735
736String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
737 Mutex::Autolock lock(mServiceLock);
738 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800739}
740
741Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700742 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700743 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700744 if (!cameraInfo) {
745 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800746 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700747 }
748
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800749 if (!mInitialized) {
750 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700751 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800752 return STATUS_ERROR(ERROR_DISCONNECTED,
753 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700754 }
755
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700756 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
757 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
758 "characteristics for system only device %s: ", String8(cameraId).string());
759 }
760
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800761 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800762
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700763
764 std::string cameraIdStr = String8(cameraId).string();
765 bool overrideForPerfClass =
766 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
767 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100768 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700769 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100770 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700771 if (res == NAME_NOT_FOUND) {
772 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
773 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
774 strerror(-res), res);
775 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700776 logServiceError(String8::format("Unable to retrieve camera characteristics for "
777 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700778 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
779 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
780 strerror(-res), res);
781 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700782 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700783 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
784 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
785 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
786 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
787 "for device %s", String8(cameraId).string());
788 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700789 int callingPid = CameraThreadState::getCallingPid();
790 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100791 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700792 // If it's not calling from cameraserver, check the permission only if
793 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
794 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100795 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700796 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700797 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100798 res = cameraInfo->removePermissionEntries(
799 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
800 &tagsRemoved);
801 if (res != OK) {
802 cameraInfo->clear();
803 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
804 " characteristics needing camera permission for device %s: %s (%d)",
805 String8(cameraId).string(), strerror(-res), res);
806 }
807 }
808
809 if (!tagsRemoved.empty()) {
810 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
811 tagsRemoved.data(), tagsRemoved.size());
812 if (res != OK) {
813 cameraInfo->clear();
814 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
815 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
816 strerror(-res), res);
817 }
818 }
819
Zhijun He2b59be82013-09-25 10:14:30 -0700820 return ret;
821}
822
Rucha Katakwar38284522021-11-10 11:25:21 -0800823Status CameraService::getTorchStrengthLevel(const String16& cameraId,
824 int32_t* torchStrength) {
825 ATRACE_CALL();
826 Mutex::Autolock l(mServiceLock);
827 if (!mInitialized) {
828 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
829 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
830 }
831
832 if(torchStrength == NULL) {
833 ALOGE("%s: strength level must not be null.", __FUNCTION__);
834 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
835 }
836
837 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
838 torchStrength);
839 if (res != OK) {
840 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
841 "strength level for device %s: %s (%d)", String8(cameraId).string(),
842 strerror(-res), res);
843 }
844 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
845 return Status::ok();
846}
847
Ruben Brunkcc776712015-02-17 20:18:47 -0800848String8 CameraService::getFormattedCurrentTime() {
849 time_t now = time(nullptr);
850 char formattedTime[64];
851 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
852 return String8(formattedTime);
853}
854
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800855Status CameraService::getCameraVendorTagDescriptor(
856 /*out*/
857 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700858 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800859 if (!mInitialized) {
860 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800861 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800862 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800863 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
864 if (globalDescriptor != nullptr) {
865 *desc = *(globalDescriptor.get());
866 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800867 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800868}
869
Emilian Peev71c73a22017-03-21 16:35:51 +0000870Status CameraService::getCameraVendorTagCache(
871 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
872 ATRACE_CALL();
873 if (!mInitialized) {
874 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
875 return STATUS_ERROR(ERROR_DISCONNECTED,
876 "Camera subsystem not available");
877 }
878 sp<VendorTagDescriptorCache> globalCache =
879 VendorTagDescriptorCache::getGlobalVendorTagCache();
880 if (globalCache != nullptr) {
881 *cache = *(globalCache.get());
882 }
883 return Status::ok();
884}
885
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700886void CameraService::clearCachedVariables() {
887 BasicClient::BasicClient::sCameraService = nullptr;
888}
889
Emilian Peevb91f1802021-03-23 14:50:28 -0700890int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700891 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800892
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800893 int deviceVersion = 0;
894
Emilian Peevf53f66e2017-04-11 14:29:43 +0100895 status_t res;
896 hardware::hidl_version maxVersion{0,0};
897 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
898 &maxVersion);
899 if (res != OK) return -1;
900 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800901
Emilian Peevf53f66e2017-04-11 14:29:43 +0100902 hardware::CameraInfo info;
903 if (facing) {
904 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800905 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100906 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700907 if (orientation) {
908 *orientation = info.orientation;
909 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800910 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100911
Igor Murashkin634a5152013-02-20 17:15:11 -0800912 return deviceVersion;
913}
914
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800915Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700916 switch(err) {
917 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800918 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800919 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
921 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800922 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800923 return STATUS_ERROR(ERROR_DISCONNECTED,
924 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700925 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800926 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
927 "Camera HAL encountered error %d: %s",
928 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700929 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800930}
931
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800932Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800933 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700934 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700935 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700936 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800937 /*out*/sp<BasicClient>* client) {
938
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700939 // Create CameraClient based on device version reported by the HAL.
940 switch(deviceVersion) {
941 case CAMERA_DEVICE_API_VERSION_1_0:
942 ALOGE("Camera using old HAL version: %d", deviceVersion);
943 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
944 "Camera device \"%s\" HAL version %d no longer supported",
945 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800946 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700947 case CAMERA_DEVICE_API_VERSION_3_0:
948 case CAMERA_DEVICE_API_VERSION_3_1:
949 case CAMERA_DEVICE_API_VERSION_3_2:
950 case CAMERA_DEVICE_API_VERSION_3_3:
951 case CAMERA_DEVICE_API_VERSION_3_4:
952 case CAMERA_DEVICE_API_VERSION_3_5:
953 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800954 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700955 case CAMERA_DEVICE_API_VERSION_3_8:
Ruben Brunkcc776712015-02-17 20:18:47 -0800956 if (effectiveApiLevel == API_1) { // Camera1 API route
957 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800958 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800959 cameraId, api1CameraId, facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700960 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800961 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800962 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
963 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800964 *client = new CameraDeviceClient(cameraService, tmp, packageName,
965 systemNativeClient, featureId, cameraId, facing, sensorOrientation,
966 clientPid, clientUid, servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800967 }
968 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700969 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800970 // Should not be reachable
971 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800973 "Camera device \"%s\" has unknown HAL version %d",
974 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800975 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800976 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800977}
978
Ruben Brunk6267b532015-04-30 17:44:07 -0700979String8 CameraService::toString(std::set<userid_t> intSet) {
980 String8 s("");
981 bool first = true;
982 for (userid_t i : intSet) {
983 if (first) {
984 s.appendFormat("%d", i);
985 first = false;
986 } else {
987 s.appendFormat(", %d", i);
988 }
989 }
990 return s;
991}
992
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800993int32_t CameraService::mapToInterface(TorchModeStatus status) {
994 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
995 switch (status) {
996 case TorchModeStatus::NOT_AVAILABLE:
997 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
998 break;
999 case TorchModeStatus::AVAILABLE_OFF:
1000 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1001 break;
1002 case TorchModeStatus::AVAILABLE_ON:
1003 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1004 break;
1005 default:
1006 ALOGW("Unknown new flash status: %d", status);
1007 }
1008 return serviceStatus;
1009}
1010
1011CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1012 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1013 switch (status) {
1014 case CameraDeviceStatus::NOT_PRESENT:
1015 serviceStatus = StatusInternal::NOT_PRESENT;
1016 break;
1017 case CameraDeviceStatus::PRESENT:
1018 serviceStatus = StatusInternal::PRESENT;
1019 break;
1020 case CameraDeviceStatus::ENUMERATING:
1021 serviceStatus = StatusInternal::ENUMERATING;
1022 break;
1023 default:
1024 ALOGW("Unknown new HAL device status: %d", status);
1025 }
1026 return serviceStatus;
1027}
1028
1029int32_t CameraService::mapToInterface(StatusInternal status) {
1030 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1031 switch (status) {
1032 case StatusInternal::NOT_PRESENT:
1033 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1034 break;
1035 case StatusInternal::PRESENT:
1036 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1037 break;
1038 case StatusInternal::ENUMERATING:
1039 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1040 break;
1041 case StatusInternal::NOT_AVAILABLE:
1042 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1043 break;
1044 case StatusInternal::UNKNOWN:
1045 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1046 break;
1047 default:
1048 ALOGW("Unknown new internal device status: %d", status);
1049 }
1050 return serviceStatus;
1051}
1052
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001053Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001054 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001055
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001056 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001057 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001058 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001059 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001060 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001061 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001062 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001063 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1064 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065 ).isOk()) {
1066 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001067 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001068 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001069}
1070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001071Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001072 /*out*/
1073 CameraParameters* parameters) {
1074
1075 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1076
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001077 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001078
1079 if (parameters == NULL) {
1080 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001081 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001082 }
1083
Ruben Brunkcc776712015-02-17 20:18:47 -08001084 String8 id = String8::format("%d", cameraId);
1085
1086 // Check if we already have parameters
1087 {
1088 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001089 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001090 auto cameraState = getCameraState(id);
1091 if (cameraState == nullptr) {
1092 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001093 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1094 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001095 }
1096 CameraParameters p = cameraState->getShimParams();
1097 if (!p.isEmpty()) {
1098 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001099 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001100 }
1101 }
1102
Jayant Chowdhary12361932018-08-27 14:46:13 -07001103 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001104 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001105 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001106 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001107 // Error already logged by callee
1108 return ret;
1109 }
1110
1111 // Check for parameters again
1112 {
1113 // Scope for service lock
1114 Mutex::Autolock lock(mServiceLock);
1115 auto cameraState = getCameraState(id);
1116 if (cameraState == nullptr) {
1117 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001118 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1119 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001120 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001121 CameraParameters p = cameraState->getShimParams();
1122 if (!p.isEmpty()) {
1123 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001124 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001125 }
1126 }
1127
Ruben Brunkcc776712015-02-17 20:18:47 -08001128 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1129 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001130 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001131}
1132
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001133// Can camera service trust the caller based on the calling UID?
1134static bool isTrustedCallingUid(uid_t uid) {
1135 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001136 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001137 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001138 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001139 return true;
1140 default:
1141 return false;
1142 }
1143}
1144
Nicholas Sauera3620332019-04-03 14:05:17 -07001145static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1146 PermissionController pc;
1147 uid = pc.getPackageUid(packageName, 0);
1148 if (uid <= 0) {
1149 ALOGE("Unknown package: '%s'", String8(packageName).string());
1150 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1151 return BAD_VALUE;
1152 }
1153
1154 if (userId < 0) {
1155 ALOGE("Invalid user: %d", userId);
1156 dprintf(err, "Invalid user: %d\n", userId);
1157 return BAD_VALUE;
1158 }
1159
1160 uid = multiuser_get_uid(userId, uid);
1161 return NO_ERROR;
1162}
1163
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001164Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001165 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1166 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001167
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001168#ifdef __BRILLO__
1169 UNUSED(clientName8);
1170 UNUSED(clientUid);
1171 UNUSED(clientPid);
1172 UNUSED(originalClientPid);
1173#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001174 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1175 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001176 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001177 return allowed;
1178 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001179#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001180
Jayant Chowdhary12361932018-08-27 14:46:13 -07001181 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001182
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001183 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1185 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001186 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1187 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001188 }
1189
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 if (getCameraState(cameraId) == nullptr) {
1191 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1192 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001193 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1194 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 }
1196
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001197 status_t err = checkIfDeviceIsUsable(cameraId);
1198 if (err != NO_ERROR) {
1199 switch(err) {
1200 case -ENODEV:
1201 case -EBUSY:
1202 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1203 "No camera device with ID \"%s\" currently available", cameraId.string());
1204 default:
1205 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1206 "Unknown error connecting to ID \"%s\"", cameraId.string());
1207 }
1208 }
1209 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001210}
1211
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001212Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001213 const String8& clientName8, int& clientUid, int& clientPid,
1214 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001215 int callingPid = CameraThreadState::getCallingPid();
1216 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001218 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001220 clientUid = callingUid;
1221 } else if (!isTrustedCallingUid(callingUid)) {
1222 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1223 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001224 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1225 "Untrusted caller (calling PID %d, UID %d) trying to "
1226 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1227 callingPid, callingUid, cameraId.string(),
1228 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229 }
1230
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001231 // Check if we can trust clientPid
1232 if (clientPid == USE_CALLING_PID) {
1233 clientPid = callingPid;
1234 } else if (!isTrustedCallingUid(callingUid)) {
1235 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1236 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001237 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1238 "Untrusted caller (calling PID %d, UID %d) trying to "
1239 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1240 callingPid, callingUid, cameraId.string(),
1241 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001242 }
1243
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001244 if (shouldRejectSystemCameraConnection(cameraId)) {
1245 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1246 cameraId.c_str());
1247 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1248 "available", cameraId.string());
1249 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001250 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1251 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1252 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1253 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1254 "found while trying to query device kind", cameraId.string());
1255
1256 }
1257
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001258 // If it's not calling from cameraserver, check the permission if the
1259 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1260 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001261 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001262 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001263 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001264 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001265 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1266 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1267 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001268 }
1269
Svet Ganova453d0d2018-01-11 15:37:58 -08001270 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001271 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001272 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001273 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1274 clientPid, clientUid);
1275 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001276 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1277 "calling UID %d proc state %" PRId32 ")",
1278 clientName8.string(), clientUid, clientPid, cameraId.string(),
1279 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001280 }
1281
Michael Grooverd1d435a2018-12-18 17:39:42 -08001282 // If sensor privacy is enabled then prevent access to the camera
1283 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1284 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1285 return STATUS_ERROR_FMT(ERROR_DISABLED,
1286 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1287 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1288 }
1289
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001290 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1291 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001292 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001293 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294
Ruben Brunk6267b532015-04-30 17:44:07 -07001295 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001296
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001297 // For non-system clients : Only allow clients who are being used by the current foreground
1298 // device user, unless calling from our own process.
1299 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001300 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001301 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1302 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1303 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001304 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1305 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1306 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001307 }
1308
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001309 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001310}
1311
1312status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1313 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001314 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001315 if (cameraState == nullptr) {
1316 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1317 cameraId.string());
1318 return -ENODEV;
1319 }
1320
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001321 StatusInternal currentStatus = cameraState->getStatus();
1322 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001323 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1324 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001325 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001326 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001327 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1328 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001329 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001330 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001331
Ruben Brunkcc776712015-02-17 20:18:47 -08001332 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001333}
1334
Ruben Brunkcc776712015-02-17 20:18:47 -08001335void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001336 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001337
Ruben Brunkcc776712015-02-17 20:18:47 -08001338 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001339 auto clientDescriptor =
1340 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001341 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001342 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1343
1344 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1345 String8(client->getPackageName()));
1346
1347 if (evicted.size() > 0) {
1348 // This should never happen - clients should already have been removed in disconnect
1349 for (auto& i : evicted) {
1350 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1351 __FUNCTION__, i->getKey().string());
1352 }
1353
1354 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1355 __FUNCTION__);
1356 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001357
1358 // And register a death notification for the client callback. Do
1359 // this last to avoid Binder policy where a nested Binder
1360 // transaction might be pre-empted to service the client death
1361 // notification if the client process dies before linkToDeath is
1362 // invoked.
1363 sp<IBinder> remoteCallback = client->getRemote();
1364 if (remoteCallback != nullptr) {
1365 remoteCallback->linkToDeath(this);
1366 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001367}
1368
1369status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1370 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001371 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 /*out*/
1373 sp<BasicClient>* client,
1374 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001375 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001377 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 DescriptorPtr clientDescriptor;
1379 {
1380 if (effectiveApiLevel == API_1) {
1381 // If we are using API1, any existing client for this camera ID with the same remote
1382 // should be returned rather than evicted to allow MediaRecorder to work properly.
1383
1384 auto current = mActiveClientManager.get(cameraId);
1385 if (current != nullptr) {
1386 auto clientSp = current->getValue();
1387 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001388 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001389 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001390 " API level, evicting prior client...");
1391 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001392 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001393 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001394 *client = clientSp;
1395 return NO_ERROR;
1396 }
1397 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001398 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001399 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001400
Ruben Brunkcc776712015-02-17 20:18:47 -08001401 // Get current active client PIDs
1402 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1403 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001404
Emilian Peev8131a262017-02-01 12:33:43 +00001405 std::vector<int> priorityScores(ownerPids.size());
1406 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001407
Emilian Peev8131a262017-02-01 12:33:43 +00001408 // Get priority scores of all active PIDs
1409 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1410 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1411 /*out*/&priorityScores[0]);
1412 if (err != OK) {
1413 ALOGE("%s: Priority score query failed: %d",
1414 __FUNCTION__, err);
1415 return err;
1416 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001417
Ruben Brunkcc776712015-02-17 20:18:47 -08001418 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001419 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001421 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001422 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001423 /* isVendorClient won't get copied over*/ false,
1424 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 }
1426 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001427
Ruben Brunkcc776712015-02-17 20:18:47 -08001428 // Get state for the given cameraId
1429 auto state = getCameraState(cameraId);
1430 if (state == nullptr) {
1431 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1432 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001433 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001434 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001435 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001436
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001437 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1438 int32_t actualState = states[states.size() - 1];
1439
1440 // Make descriptor for incoming client. We store the oomScoreOffset
1441 // since we might need it later on new handleEvictionsLocked and
1442 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001443 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001444 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001445 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001446 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001447
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001448 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1449
Ruben Brunkcc776712015-02-17 20:18:47 -08001450 // Find clients that would be evicted
1451 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1452
1453 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1454 // background, so we cannot do evictions
1455 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1456 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1457 " priority).", clientPid);
1458
1459 sp<BasicClient> clientSp = clientDescriptor->getValue();
1460 String8 curTime = getFormattedCurrentTime();
1461 auto incompatibleClients =
1462 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1463
1464 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001465 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001466 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001467 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001468
1469 for (auto& i : incompatibleClients) {
1470 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001471 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1472 i->getKey().string(),
1473 String8{i->getValue()->getPackageName()}.string(),
1474 i->getOwnerId(), i->getPriority().getScore(),
1475 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001476 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001477 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001478 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001479 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001480 }
1481
1482 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001483 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001484 mEventLog.add(msg);
1485
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001486 auto current = mActiveClientManager.get(cameraId);
1487 if (current != nullptr) {
1488 return -EBUSY; // CAMERA_IN_USE
1489 } else {
1490 return -EUSERS; // MAX_CAMERAS_IN_USE
1491 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001492 }
1493
1494 for (auto& i : evicted) {
1495 sp<BasicClient> clientSp = i->getValue();
1496 if (clientSp.get() == nullptr) {
1497 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1498
1499 // TODO: Remove this
1500 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1501 __FUNCTION__);
1502 mActiveClientManager.remove(i);
1503 continue;
1504 }
1505
1506 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1507 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001508 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001509
Ruben Brunkcc776712015-02-17 20:18:47 -08001510 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001511 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001512 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1513 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001514 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001515 i->getOwnerId(), i->getPriority().getScore(),
1516 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001517 packageName.string(), clientPid, clientPriority.getScore(),
1518 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001519
1520 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001521 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001522 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001523 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001524 }
1525
Ruben Brunkcc776712015-02-17 20:18:47 -08001526 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1527 // other clients from connecting in mServiceLockWrapper if held
1528 mServiceLock.unlock();
1529
1530 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001531 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001532
1533 // Destroy evicted clients
1534 for (auto& i : evictedClients) {
1535 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001536 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001537 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001538
Jayant Chowdhary12361932018-08-27 14:46:13 -07001539 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001540
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001541 for (const auto& i : evictedClients) {
1542 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1543 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1544 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1545 if (ret == TIMED_OUT) {
1546 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1547 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1548 mActiveClientManager.toString().string());
1549 return -EBUSY;
1550 }
1551 if (ret != NO_ERROR) {
1552 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1553 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1554 ret, mActiveClientManager.toString().string());
1555 return ret;
1556 }
1557 }
1558
1559 evictedClients.clear();
1560
Ruben Brunkcc776712015-02-17 20:18:47 -08001561 // Once clients have been disconnected, relock
1562 mServiceLock.lock();
1563
1564 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1565 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1566 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001567 }
1568
Ruben Brunkcc776712015-02-17 20:18:47 -08001569 *partial = clientDescriptor;
1570 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001571}
1572
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001573Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001574 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001575 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001576 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001577 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001578 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001579 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001580 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001582
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001583 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001585
1586 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001587 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001588 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001589 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001590 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001591
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001592 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001593 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001595 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001596 }
1597
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001598 *device = client;
1599 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001600}
1601
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001602bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1603 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001604 // If the client is not a vendor client, don't add listener if
1605 // a) the camera is a publicly hidden secure camera OR
1606 // b) the camera is a system only camera and the client doesn't
1607 // have android.permission.SYSTEM_CAMERA permissions.
1608 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1609 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1610 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001611 return true;
1612 }
1613 return false;
1614}
1615
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001616bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1617 // Rules for rejection:
1618 // 1) If cameraserver tries to access this camera device, accept the
1619 // connection.
1620 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001621 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001622 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1623 // and the serving thread is a non hwbinder thread, the client must have
1624 // android.permission.SYSTEM_CAMERA permissions to connect.
1625
1626 int cPid = CameraThreadState::getCallingPid();
1627 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001628 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001629 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1630 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001631 // This isn't a known camera ID, so it's not a system camera
1632 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1633 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001634 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001635
1636 // (1) Cameraserver trying to connect, accept.
1637 if (CameraThreadState::getCallingPid() == getpid()) {
1638 return false;
1639 }
1640 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001641 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001642 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1643 return true;
1644 }
1645 // (3) Here we only check for permissions if it is a system only camera device. This is since
1646 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1647 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1648 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001649 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001650 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001651 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1652 cameraId.c_str());
1653 return true;
1654 }
1655
1656 return false;
1657}
1658
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001659Status CameraService::connectDevice(
1660 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001661 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001662 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001663 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001664 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001665 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001666 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001667
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001668 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001669 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001670 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001672 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001673 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001674 bool systemNativeClient = false;
1675 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1676 std::string systemClient =
1677 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1678 clientPackageNameAdj = String16(systemClient.c_str());
1679 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001680 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001681
1682 if (oomScoreOffset < 0) {
1683 String8 msg =
1684 String8::format("Cannot increase the priority of a client %s pid %d for "
1685 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1686 id.string());
1687 ALOGE("%s: %s", __FUNCTION__, msg.string());
1688 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1689 }
1690
1691 // enforce system camera permissions
1692 if (oomScoreOffset > 0 &&
1693 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1694 String8 msg =
1695 String8::format("Cannot change the priority of a client %s pid %d for "
1696 "camera id %s without SYSTEM_CAMERA permissions",
1697 String8(clientPackageNameAdj).string(), callingPid, id.string());
1698 ALOGE("%s: %s", __FUNCTION__, msg.string());
1699 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1700 }
1701
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001702 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001703 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001704 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001705 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001706
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001708 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001709 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001710 }
1711
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001712 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001713 Mutex::Autolock lock(mServiceLock);
1714
1715 // Clear the previous cached logs and reposition the
1716 // file offset to beginning of the file to log new data.
1717 // If either truncate or lseek fails, close the previous file and create a new one.
1718 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1719 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1720 // Close the previous memfd.
1721 close(mMemFd);
1722 // If failure to wipe the data, then create a new file and
1723 // assign the new value to mMemFd.
1724 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1725 if (mMemFd == -1) {
1726 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1727 }
1728 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001729 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001730}
1731
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001732template<class CALLBACK, class CLIENT>
1733Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001734 int api1CameraId, const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001735 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001736 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001737 /*out*/sp<CLIENT>& device) {
1738 binder::Status ret = binder::Status::ok();
1739
1740 String8 clientName8(clientPackageName);
1741
1742 int originalClientPid = 0;
1743
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001744 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001745 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001746 static_cast<int>(effectiveApiLevel));
1747
Shuzhen Wang316781a2020-08-18 18:11:01 -07001748 nsecs_t openTimeNs = systemTime();
1749
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001750 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001751 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001752 int orientation = 0;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001753 bool isNonSystemNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001754 {
1755 // Acquire mServiceLock and prevent other clients from connecting
1756 std::unique_ptr<AutoConditionLock> lock =
1757 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1758
1759 if (lock == nullptr) {
1760 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1761 , clientPid);
1762 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1763 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1764 cameraId.string(), clientName8.string(), clientPid);
1765 }
1766
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001767 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001768 if(!(ret = validateConnectLocked(cameraId, clientName8,
1769 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1770 return ret;
1771 }
1772
1773 // Check the shim parameters after acquiring lock, if they have already been updated and
1774 // we were doing a shim update, return immediately
1775 if (shimUpdateOnly) {
1776 auto cameraState = getCameraState(cameraId);
1777 if (cameraState != nullptr) {
1778 if (!cameraState->getShimParams().isEmpty()) return ret;
1779 }
1780 }
1781
1782 status_t err;
1783
1784 sp<BasicClient> clientTmp = nullptr;
1785 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1786 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001787 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
1788 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001789 switch (err) {
1790 case -ENODEV:
1791 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1792 "No camera device with ID \"%s\" currently available",
1793 cameraId.string());
1794 case -EBUSY:
1795 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1796 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1797 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001798 case -EUSERS:
1799 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1800 "Too many cameras already open, cannot open camera \"%s\"",
1801 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001802 default:
1803 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1804 "Unexpected error %s (%d) opening camera \"%s\"",
1805 strerror(-err), err, cameraId.string());
1806 }
1807 }
1808
1809 if (clientTmp.get() != nullptr) {
1810 // Handle special case for API1 MediaRecorder where the existing client is returned
1811 device = static_cast<CLIENT*>(clientTmp.get());
1812 return ret;
1813 }
1814
1815 // give flashlight a chance to close devices if necessary.
1816 mFlashlight->prepareDeviceOpen(cameraId);
1817
Emilian Peevb91f1802021-03-23 14:50:28 -07001818 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001819 if (facing == -1) {
1820 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1821 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1822 "Unable to get camera device \"%s\" facing", cameraId.string());
1823 }
1824
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001825 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001826 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1827 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001828 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
1829 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001830 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001831 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001832 /*out*/&tmp)).isOk()) {
1833 return ret;
1834 }
1835 client = static_cast<CLIENT*>(tmp.get());
1836
1837 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1838 __FUNCTION__);
1839
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001840 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1841 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001842 if (err != OK) {
1843 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001844 // Errors could be from the HAL module open call or from AppOpsManager
1845 switch(err) {
1846 case BAD_VALUE:
1847 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1848 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1849 case -EBUSY:
1850 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1851 "Camera \"%s\" is already open", cameraId.string());
1852 case -EUSERS:
1853 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1854 "Too many cameras already open, cannot open camera \"%s\"",
1855 cameraId.string());
1856 case PERMISSION_DENIED:
1857 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1858 "No permission to open camera \"%s\"", cameraId.string());
1859 case -EACCES:
1860 return STATUS_ERROR_FMT(ERROR_DISABLED,
1861 "Camera \"%s\" disabled by policy", cameraId.string());
1862 case -ENODEV:
1863 default:
1864 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1865 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1866 strerror(-err), err);
1867 }
1868 }
1869
1870 // Update shim paremeters for legacy clients
1871 if (effectiveApiLevel == API_1) {
1872 // Assume we have always received a Client subclass for API1
1873 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1874 String8 rawParams = shimClient->getParameters();
1875 CameraParameters params(rawParams);
1876
1877 auto cameraState = getCameraState(cameraId);
1878 if (cameraState != nullptr) {
1879 cameraState->setShimParams(params);
1880 } else {
1881 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1882 __FUNCTION__, cameraId.string());
1883 }
1884 }
1885
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001886 // Set rotate-and-crop override behavior
1887 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1888 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001889 } else if (effectiveApiLevel == API_2) {
Emilian Peev065b2c12021-11-23 13:12:57 -08001890
1891 client->setRotateAndCropOverride(
1892 CameraServiceProxyWrapper::getRotateAndCropOverride(
1893 clientPackageName, facing, multiuser_get_user_id(clientUid)));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001894 }
1895
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001896 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001897 bool isCameraPrivacyEnabled =
1898 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001899 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001900 client->setCameraMute(
1901 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1902 } else if (isCameraPrivacyEnabled) {
1903 // no camera mute supported, but privacy is on! => disconnect
1904 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1905 String8(client->getPackageName()).string(), cameraId.string());
1906 // Do not hold mServiceLock while disconnecting clients, but
1907 // retain the condition blocking other clients from connecting
1908 // in mServiceLockWrapper if held.
1909 mServiceLock.unlock();
1910 // Clear caller identity temporarily so client disconnect PID
1911 // checks work correctly
1912 int64_t token = CameraThreadState::clearCallingIdentity();
1913 // Note AppOp to trigger the "Unblock" dialog
1914 client->noteAppOp();
1915 client->disconnect();
1916 CameraThreadState::restoreCallingIdentity(token);
1917 // Reacquire mServiceLock
1918 mServiceLock.lock();
1919
1920 return STATUS_ERROR_FMT(ERROR_DISABLED,
1921 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001922 }
1923
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001924 if (shimUpdateOnly) {
1925 // If only updating legacy shim parameters, immediately disconnect client
1926 mServiceLock.unlock();
1927 client->disconnect();
1928 mServiceLock.lock();
1929 } else {
1930 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001931 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001932 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001933
1934 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001935 } // lock is destroyed, allow further connect calls
1936
1937 // Important: release the mutex here so the client can call back into the service from its
1938 // destructor (can be at the end of the call)
1939 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001940
1941 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1942 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001943 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001944
Cliff Wud3a05312021-04-26 23:07:31 +08001945 {
1946 Mutex::Autolock lock(mInjectionParametersLock);
1947 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1948 mInjectionInitPending = false;
1949 status_t res = NO_ERROR;
1950 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1951 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08001952 sp<BasicClient> clientSp = clientDescriptor->getValue();
1953 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
1954 if(res != OK) {
1955 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1956 "No camera device with ID \"%s\" currently available",
1957 mInjectionExternalCamId.string());
1958 }
1959 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08001960 if (res != OK) {
1961 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1962 }
1963 } else {
1964 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1965 __FUNCTION__, mInjectionInternalCamId.string());
1966 res = NO_INIT;
1967 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1968 }
1969 }
1970 }
1971
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001972 return ret;
1973}
1974
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001975status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1976 if (offlineClient.get() == nullptr) {
1977 return BAD_VALUE;
1978 }
1979
1980 {
1981 // Acquire mServiceLock and prevent other clients from connecting
1982 std::unique_ptr<AutoConditionLock> lock =
1983 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1984
1985 if (lock == nullptr) {
1986 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1987 , __FUNCTION__, offlineClient->getClientPid());
1988 return TIMED_OUT;
1989 }
1990
1991 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1992 if (onlineClientDesc.get() == nullptr) {
1993 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1994 cameraId.c_str());
1995 return BAD_VALUE;
1996 }
1997
1998 // Offline clients do not evict or conflict with other online devices. Resource sharing
1999 // conflicts are handled by the camera provider which will either succeed or fail before
2000 // reaching this method.
2001 const auto& onlinePriority = onlineClientDesc->getPriority();
2002 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2003 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2004 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002005 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002006 // native clients don't have offline processing support.
2007 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002008
2009 // Allow only one offline device per camera
2010 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2011 if (!incompatibleClients.empty()) {
2012 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2013 return BAD_VALUE;
2014 }
2015
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002016 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2017 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002018 if (err != OK) {
2019 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2020 return err;
2021 }
2022
2023 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2024 if (evicted.size() > 0) {
2025 for (auto& i : evicted) {
2026 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2027 __FUNCTION__, i->getKey().string());
2028 }
2029
2030 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2031 "properly", __FUNCTION__);
2032
2033 return BAD_VALUE;
2034 }
2035
2036 logConnectedOffline(offlineClientDesc->getKey(),
2037 static_cast<int>(offlineClientDesc->getOwnerId()),
2038 String8(offlineClient->getPackageName()));
2039
2040 sp<IBinder> remoteCallback = offlineClient->getRemote();
2041 if (remoteCallback != nullptr) {
2042 remoteCallback->linkToDeath(this);
2043 }
2044 } // lock is destroyed, allow further connect calls
2045
2046 return OK;
2047}
2048
Rucha Katakwar38284522021-11-10 11:25:21 -08002049Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2050 const sp<IBinder>& clientBinder) {
2051 Mutex::Autolock lock(mServiceLock);
2052
2053 ATRACE_CALL();
2054 if (clientBinder == nullptr) {
2055 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2056 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2057 "Torch client binder in null.");
2058 }
2059
2060 String8 id = String8(cameraId.string());
2061 int uid = CameraThreadState::getCallingUid();
2062
2063 if (shouldRejectSystemCameraConnection(id)) {
2064 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2065 "for system only device %s: ", id.string());
2066 }
2067
2068 // verify id is valid
2069 auto state = getCameraState(id);
2070 if (state == nullptr) {
2071 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2072 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2073 "Camera ID \"%s\" is a not valid camera ID", id.string());
2074 }
2075
2076 StatusInternal cameraStatus = state->getStatus();
2077 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2078 cameraStatus != StatusInternal::PRESENT) {
2079 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2080 (int)cameraStatus);
2081 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2082 "Camera ID \"%s\" is a not valid camera ID", id.string());
2083 }
2084
2085 {
2086 Mutex::Autolock al(mTorchStatusMutex);
2087 TorchModeStatus status;
2088 status_t err = getTorchStatusLocked(id, &status);
2089 if (err != OK) {
2090 if (err == NAME_NOT_FOUND) {
2091 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2092 "Camera \"%s\" does not have a flash unit", id.string());
2093 }
2094 ALOGE("%s: getting current torch status failed for camera %s",
2095 __FUNCTION__, id.string());
2096 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2097 "Error changing torch strength level for camera \"%s\": %s (%d)",
2098 id.string(), strerror(-err), err);
2099 }
2100
2101 if (status == TorchModeStatus::NOT_AVAILABLE) {
2102 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2103 ALOGE("%s: torch mode of camera %s is not available because "
2104 "camera is in use.", __FUNCTION__, id.string());
2105 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2106 "Torch for camera \"%s\" is not available due to an existing camera user",
2107 id.string());
2108 } else {
2109 ALOGE("%s: torch mode of camera %s is not available due to "
2110 "insufficient resources", __FUNCTION__, id.string());
2111 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2112 "Torch for camera \"%s\" is not available due to insufficient resources",
2113 id.string());
2114 }
2115 }
2116 }
2117
2118 {
2119 Mutex::Autolock al(mTorchUidMapMutex);
2120 updateTorchUidMapLocked(cameraId, uid);
2121 }
2122 // Check if the current torch strength level is same as the new one.
2123 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2124 id.string(), torchStrength);
2125
2126 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2127
2128 if (err != OK) {
2129 int32_t errorCode;
2130 String8 msg;
2131 switch (err) {
2132 case -ENOSYS:
2133 msg = String8::format("Camera \"%s\" has no flashlight.",
2134 id.string());
2135 errorCode = ERROR_ILLEGAL_ARGUMENT;
2136 break;
2137 case -EBUSY:
2138 msg = String8::format("Camera \"%s\" is in use",
2139 id.string());
2140 errorCode = ERROR_CAMERA_IN_USE;
2141 break;
2142 default:
2143 msg = String8::format("Changing torch strength level failed.");
2144 errorCode = ERROR_INVALID_OPERATION;
2145
2146 }
2147 ALOGE("%s: %s", __FUNCTION__, msg.string());
2148 return STATUS_ERROR(errorCode, msg.string());
2149 }
2150
2151 {
2152 // update the link to client's death
2153 // Store the last client that turns on each camera's torch mode.
2154 Mutex::Autolock al(mTorchClientMapMutex);
2155 ssize_t index = mTorchClientMap.indexOfKey(id);
2156 if (index == NAME_NOT_FOUND) {
2157 mTorchClientMap.add(id, clientBinder);
2158 } else {
2159 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2160 mTorchClientMap.replaceValueAt(index, clientBinder);
2161 }
2162 clientBinder->linkToDeath(this);
2163 }
2164
2165 int clientPid = CameraThreadState::getCallingPid();
2166 const char *id_cstr = id.c_str();
2167 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2168 __FUNCTION__, id_cstr, torchStrength, clientPid);
2169 if (!shouldSkipTorchStrengthUpdates) {
2170 broadcastTorchStrengthLevel(id, torchStrength);
2171 }
2172 return Status::ok();
2173}
2174
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002175Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002176 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002177 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002178
2179 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002180 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002181 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002182 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2183 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002184 }
2185
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002186 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002187 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002188
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002189 if (shouldRejectSystemCameraConnection(id)) {
2190 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2191 " for system only device %s: ", id.string());
2192 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002193 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002194 auto state = getCameraState(id);
2195 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002196 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002197 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2198 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002199 }
2200
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002201 StatusInternal cameraStatus = state->getStatus();
2202 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002203 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2204 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002205 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2206 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002207 }
2208
2209 {
2210 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002211 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002212 status_t err = getTorchStatusLocked(id, &status);
2213 if (err != OK) {
2214 if (err == NAME_NOT_FOUND) {
2215 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2216 "Camera \"%s\" does not have a flash unit", id.string());
2217 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002218 ALOGE("%s: getting current torch status failed for camera %s",
2219 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2221 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2222 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002223 }
2224
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002225 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002226 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002227 ALOGE("%s: torch mode of camera %s is not available because "
2228 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2230 "Torch for camera \"%s\" is not available due to an existing camera user",
2231 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002232 } else {
2233 ALOGE("%s: torch mode of camera %s is not available due to "
2234 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002235 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2236 "Torch for camera \"%s\" is not available due to insufficient resources",
2237 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002238 }
2239 }
2240 }
2241
Ruben Brunk99e69712015-05-26 17:25:07 -07002242 {
2243 // Update UID map - this is used in the torch status changed callbacks, so must be done
2244 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002245 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002246 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002247 }
2248
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002250
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002251 if (err != OK) {
2252 int32_t errorCode;
2253 String8 msg;
2254 switch (err) {
2255 case -ENOSYS:
2256 msg = String8::format("Camera \"%s\" has no flashlight",
2257 id.string());
2258 errorCode = ERROR_ILLEGAL_ARGUMENT;
2259 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002260 case -EBUSY:
2261 msg = String8::format("Camera \"%s\" is in use",
2262 id.string());
2263 errorCode = ERROR_CAMERA_IN_USE;
2264 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265 default:
2266 msg = String8::format(
2267 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2268 id.string(), enabled, strerror(-err), err);
2269 errorCode = ERROR_INVALID_OPERATION;
2270 }
2271 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002272 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002273 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002274 }
2275
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002276 {
2277 // update the link to client's death
2278 Mutex::Autolock al(mTorchClientMapMutex);
2279 ssize_t index = mTorchClientMap.indexOfKey(id);
2280 if (enabled) {
2281 if (index == NAME_NOT_FOUND) {
2282 mTorchClientMap.add(id, clientBinder);
2283 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002284 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002285 mTorchClientMap.replaceValueAt(index, clientBinder);
2286 }
2287 clientBinder->linkToDeath(this);
2288 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002289 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002290 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002291 }
2292
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002293 int clientPid = CameraThreadState::getCallingPid();
2294 const char *id_cstr = id.c_str();
2295 const char *torchState = enabled ? "on" : "off";
2296 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2297 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002299}
2300
Rucha Katakwar38284522021-11-10 11:25:21 -08002301void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2302 String8 id = String8(cameraId.string());
2303 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2304 mTorchUidMap[id].first = uid;
2305 mTorchUidMap[id].second = uid;
2306 } else {
2307 // Set the pending UID
2308 mTorchUidMap[id].first = uid;
2309 }
2310}
2311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312Status CameraService::notifySystemEvent(int32_t eventId,
2313 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002314 const int pid = CameraThreadState::getCallingPid();
2315 const int selfPid = getpid();
2316
2317 // Permission checks
2318 if (pid != selfPid) {
2319 // Ensure we're being called by system_server, or similar process with
2320 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002321 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002322 const int uid = CameraThreadState::getCallingUid();
2323 ALOGE("Permission Denial: cannot send updates to camera service about system"
2324 " events from pid=%d, uid=%d", pid, uid);
2325 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002326 "No permission to send updates to camera service about system events"
2327 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002328 }
2329 }
2330
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002331 ATRACE_CALL();
2332
Ruben Brunk36597b22015-03-20 22:15:57 -07002333 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002334 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002335 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002336 // from a system server crash
2337 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002338 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002339 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002340 break;
2341 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002342 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2343 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2344 // Notify CameraProviderManager for lazy HALs
2345 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2346 std::to_string(args[0]));
2347 break;
2348 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002349 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002350 default: {
2351 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2352 eventId);
2353 break;
2354 }
2355 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002357}
2358
Emilian Peev53722fa2019-02-22 17:47:20 -08002359void CameraService::notifyMonitoredUids() {
2360 Mutex::Autolock lock(mStatusListenerLock);
2361
2362 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002363 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002364 if (!ret.isOk()) {
2365 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2366 ret.exceptionCode());
2367 }
2368 }
2369}
2370
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002371Status CameraService::notifyDeviceStateChange(int64_t newState) {
2372 const int pid = CameraThreadState::getCallingPid();
2373 const int selfPid = getpid();
2374
2375 // Permission checks
2376 if (pid != selfPid) {
2377 // Ensure we're being called by system_server, or similar process with
2378 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002379 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002380 const int uid = CameraThreadState::getCallingUid();
2381 ALOGE("Permission Denial: cannot send updates to camera service about device"
2382 " state changes from pid=%d, uid=%d", pid, uid);
2383 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2384 "No permission to send updates to camera service about device state"
2385 " changes from pid=%d, uid=%d", pid, uid);
2386 }
2387 }
2388
2389 ATRACE_CALL();
2390
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002391 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002392
2393 return Status::ok();
2394}
2395
Emilian Peev8b64f282021-03-25 16:49:57 -07002396Status CameraService::notifyDisplayConfigurationChange() {
2397 ATRACE_CALL();
2398 const int callingPid = CameraThreadState::getCallingPid();
2399 const int selfPid = getpid();
2400
2401 // Permission checks
2402 if (callingPid != selfPid) {
2403 // Ensure we're being called by system_server, or similar process with
2404 // permissions to notify the camera service about system events
2405 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2406 const int uid = CameraThreadState::getCallingUid();
2407 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2408 " changes from pid=%d, uid=%d", callingPid, uid);
2409 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2410 "No permission to send updates to camera service about orientation"
2411 " changes from pid=%d, uid=%d", callingPid, uid);
2412 }
2413 }
2414
2415 Mutex::Autolock lock(mServiceLock);
2416
2417 // Don't do anything if rotate-and-crop override via cmd is active
2418 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2419
2420 const auto clients = mActiveClientManager.getAll();
2421 for (auto& current : clients) {
2422 if (current != nullptr) {
2423 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002424 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev065b2c12021-11-23 13:12:57 -08002425 basicClient->setRotateAndCropOverride(
2426 CameraServiceProxyWrapper::getRotateAndCropOverride(
2427 basicClient->getPackageName(),
2428 basicClient->getCameraFacing(),
2429 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002430 }
2431 }
2432 }
2433
2434 return Status::ok();
2435}
2436
2437Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002438 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2439 ATRACE_CALL();
2440 if (!concurrentCameraIds) {
2441 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2442 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2443 }
2444
2445 if (!mInitialized) {
2446 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002447 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002448 return STATUS_ERROR(ERROR_DISCONNECTED,
2449 "Camera subsystem is not available");
2450 }
2451 // First call into the provider and get the set of concurrent camera
2452 // combinations
2453 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002454 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002455 for (auto &combination : concurrentCameraCombinations) {
2456 std::vector<std::string> validCombination;
2457 for (auto &cameraId : combination) {
2458 // if the camera state is not present, skip
2459 String8 cameraIdStr(cameraId.c_str());
2460 auto state = getCameraState(cameraIdStr);
2461 if (state == nullptr) {
2462 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2463 continue;
2464 }
2465 StatusInternal status = state->getStatus();
2466 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2467 continue;
2468 }
2469 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2470 continue;
2471 }
2472 validCombination.push_back(cameraId);
2473 }
2474 if (validCombination.size() != 0) {
2475 concurrentCameraIds->push_back(std::move(validCombination));
2476 }
2477 }
2478 return Status::ok();
2479}
2480
2481Status CameraService::isConcurrentSessionConfigurationSupported(
2482 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002483 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002484 if (!isSupported) {
2485 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2486 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2487 }
2488
2489 if (!mInitialized) {
2490 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2491 return STATUS_ERROR(ERROR_DISCONNECTED,
2492 "Camera subsystem is not available");
2493 }
2494
2495 // Check for camera permissions
2496 int callingPid = CameraThreadState::getCallingPid();
2497 int callingUid = CameraThreadState::getCallingUid();
2498 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2499 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2500 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2501 "android.permission.CAMERA needed to call"
2502 "isConcurrentSessionConfigurationSupported");
2503 }
2504
2505 status_t res =
2506 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002507 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2508 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002509 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002510 logServiceError(String8::format("Unable to query session configuration support"),
2511 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002512 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2513 "support %s (%d)", strerror(-res), res);
2514 }
2515 return Status::ok();
2516}
2517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002518Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2519 /*out*/
2520 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002521 return addListenerHelper(listener, cameraStatuses);
2522}
2523
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002524binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2525 std::vector<hardware::CameraStatus>* cameraStatuses) {
2526 return addListenerHelper(listener, cameraStatuses, false, true);
2527}
2528
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002529Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2530 /*out*/
2531 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002532 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002533
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002534 ATRACE_CALL();
2535
Igor Murashkinbfc99152013-02-27 12:55:20 -08002536 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002537
Ruben Brunk3450ba72015-06-16 11:00:37 -07002538 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002539 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002540 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002541 }
2542
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002543 auto clientUid = CameraThreadState::getCallingUid();
2544 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002545 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002546 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002547
Igor Murashkinbfc99152013-02-27 12:55:20 -08002548 Mutex::Autolock lock(mServiceLock);
2549
Ruben Brunkcc776712015-02-17 20:18:47 -08002550 {
2551 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002552 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002553 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002554 ALOGW("%s: Tried to add listener %p which was already subscribed",
2555 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002556 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002557 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002558 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002559
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002560 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002561 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2562 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002563 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002564 if (ret != NO_ERROR) {
2565 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2566 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002567 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002568 ALOGE("%s: %s", __FUNCTION__, msg.string());
2569 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2570 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002571 // The listener still needs to be added to the list of listeners, regardless of what
2572 // permissions the listener process has / whether it is a vendor listener. Since it might be
2573 // eligible to listen to other camera ids.
2574 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002575 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002576 }
2577
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002578 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002579 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002580 Mutex::Autolock lock(mCameraStatesLock);
2581 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002582 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002583 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2584 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002585 }
2586 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002587 // Remove the camera statuses that should be hidden from the client, we do
2588 // this after collecting the states in order to avoid holding
2589 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2590 // the same time.
2591 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2592 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2593 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2594 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2595 ALOGE("%s: Invalid camera id %s, skipping status update",
2596 __FUNCTION__, s.cameraId.c_str());
2597 return true;
2598 }
2599 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2600 clientUid);}), cameraStatuses->end());
2601
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002602 //cameraStatuses will have non-eligible camera ids removed.
2603 std::set<String16> idsChosenForCallback;
2604 for (const auto &s : *cameraStatuses) {
2605 idsChosenForCallback.insert(String16(s.cameraId));
2606 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002607
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002608 /*
2609 * Immediately signal current torch status to this listener only
2610 * This may be a subset of all the devices, so don't include it in the response directly
2611 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002612 {
2613 Mutex::Autolock al(mTorchStatusMutex);
2614 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002615 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002616 // The camera id is visible to the client. Fine to send torch
2617 // callback.
2618 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2619 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2620 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002621 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002622 }
2623
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002624 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002625}
Ruben Brunkcc776712015-02-17 20:18:47 -08002626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002627Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002628 ATRACE_CALL();
2629
Igor Murashkinbfc99152013-02-27 12:55:20 -08002630 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2631
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002632 if (listener == 0) {
2633 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002634 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002635 }
2636
Igor Murashkinbfc99152013-02-27 12:55:20 -08002637 Mutex::Autolock lock(mServiceLock);
2638
Ruben Brunkcc776712015-02-17 20:18:47 -08002639 {
2640 Mutex::Autolock lock(mStatusListenerLock);
2641 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002642 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2643 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2644 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002645 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002646 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002647 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002648 }
2649 }
2650
2651 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2652 __FUNCTION__, listener.get());
2653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002654 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002655}
2656
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002657Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002658
2659 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002660 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2661
2662 if (parameters == NULL) {
2663 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002664 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002665 }
2666
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002667 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002668
2669 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002670 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002671 // Error logged by caller
2672 return ret;
2673 }
2674
2675 String8 shimParamsString8 = shimParams.flatten();
2676 String16 shimParamsString16 = String16(shimParamsString8);
2677
2678 *parameters = shimParamsString16;
2679
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002680 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002681}
2682
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002683Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2684 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002685 ATRACE_CALL();
2686
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002687 const String8 id = String8(cameraId);
2688
2689 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002690
2691 switch (apiVersion) {
2692 case API_VERSION_1:
2693 case API_VERSION_2:
2694 break;
2695 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002696 String8 msg = String8::format("Unknown API version %d", apiVersion);
2697 ALOGE("%s: %s", __FUNCTION__, msg.string());
2698 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002699 }
2700
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002701 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002702 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002703 case CAMERA_DEVICE_API_VERSION_1_0:
2704 case CAMERA_DEVICE_API_VERSION_3_0:
2705 case CAMERA_DEVICE_API_VERSION_3_1:
2706 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002707 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2708 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002709 *isSupported = false;
2710 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002711 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2712 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002713 *isSupported = true;
2714 }
2715 break;
2716 case CAMERA_DEVICE_API_VERSION_3_2:
2717 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002718 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002719 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002720 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002721 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002722 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002723 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2724 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002725 *isSupported = true;
2726 break;
2727 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002728 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002729 ALOGE("%s: %s", __FUNCTION__, msg.string());
2730 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002731 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002732 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002733 String8 msg = String8::format("Unknown device version %x for device %s",
2734 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002735 ALOGE("%s: %s", __FUNCTION__, msg.string());
2736 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2737 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002738 }
2739
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002740 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002741}
2742
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002743Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2744 /*out*/ bool *isSupported) {
2745 ATRACE_CALL();
2746
2747 const String8 id = String8(cameraId);
2748
2749 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2750 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2751
2752 return Status::ok();
2753}
2754
Cliff Wud8cae102021-03-11 01:37:42 +08002755Status CameraService::injectCamera(
2756 const String16& packageName, const String16& internalCamId,
2757 const String16& externalCamId,
2758 const sp<ICameraInjectionCallback>& callback,
2759 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002760 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002761 ATRACE_CALL();
2762
2763 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2764 const int pid = CameraThreadState::getCallingPid();
2765 const int uid = CameraThreadState::getCallingUid();
2766 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2767 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2768 "Permission Denial: no permission to inject camera");
2769 }
2770
2771 ALOGV(
2772 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2773 "%s",
2774 __FUNCTION__, String8(packageName).string(),
2775 String8(internalCamId).string(), String8(externalCamId).string());
2776
Cliff Wud3a05312021-04-26 23:07:31 +08002777 {
2778 Mutex::Autolock lock(mInjectionParametersLock);
2779 mInjectionInternalCamId = String8(internalCamId);
2780 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002781 mInjectionStatusListener->addListener(callback);
2782 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002783 status_t res = NO_ERROR;
2784 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2785 // If the client already exists, we can directly connect to the camera device through the
2786 // client's injectCamera(), otherwise we need to wait until the client is established
2787 // (execute connectHelper()) before injecting the camera to the camera device.
2788 if (clientDescriptor != nullptr) {
2789 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002790 sp<BasicClient> clientSp = clientDescriptor->getValue();
2791 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2792 if(res != OK) {
2793 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2794 "No camera device with ID \"%s\" currently available",
2795 mInjectionExternalCamId.string());
2796 }
2797 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002798 if(res != OK) {
2799 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2800 }
2801 } else {
2802 mInjectionInitPending = true;
2803 }
2804 }
Cliff Wud8cae102021-03-11 01:37:42 +08002805
Cliff Wud3a05312021-04-26 23:07:31 +08002806 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002807}
2808
Ruben Brunkcc776712015-02-17 20:18:47 -08002809void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002810 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002811 for (auto& i : mActiveClientManager.getAll()) {
2812 auto clientSp = i->getValue();
2813 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002814 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002815 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002816 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002817 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002818 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002819}
2820
Ruben Brunkcc776712015-02-17 20:18:47 -08002821bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002822 bool ret = false;
2823 {
2824 // Acquire mServiceLock and prevent other clients from connecting
2825 std::unique_ptr<AutoConditionLock> lock =
2826 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002827
Igor Murashkin634a5152013-02-20 17:15:11 -08002828
Ruben Brunkcc776712015-02-17 20:18:47 -08002829 std::vector<sp<BasicClient>> evicted;
2830 for (auto& i : mActiveClientManager.getAll()) {
2831 auto clientSp = i->getValue();
2832 if (clientSp.get() == nullptr) {
2833 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2834 mActiveClientManager.remove(i);
2835 continue;
2836 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002837 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002838 mActiveClientManager.remove(i);
2839 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002840
Ruben Brunkcc776712015-02-17 20:18:47 -08002841 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002842 clientSp->notifyError(
2843 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002844 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002845 }
2846 }
2847
Ruben Brunkcc776712015-02-17 20:18:47 -08002848 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2849 // other clients from connecting in mServiceLockWrapper if held
2850 mServiceLock.unlock();
2851
Ruben Brunk36597b22015-03-20 22:15:57 -07002852 // Do not clear caller identity, remote caller should be client proccess
2853
Ruben Brunkcc776712015-02-17 20:18:47 -08002854 for (auto& i : evicted) {
2855 if (i.get() != nullptr) {
2856 i->disconnect();
2857 ret = true;
2858 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002859 }
2860
Ruben Brunkcc776712015-02-17 20:18:47 -08002861 // Reacquire mServiceLock
2862 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002863
Ruben Brunkcc776712015-02-17 20:18:47 -08002864 } // lock is destroyed, allow further connect calls
2865
2866 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002867}
2868
Ruben Brunkcc776712015-02-17 20:18:47 -08002869std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2870 const String8& cameraId) const {
2871 std::shared_ptr<CameraState> state;
2872 {
2873 Mutex::Autolock lock(mCameraStatesLock);
2874 auto iter = mCameraStates.find(cameraId);
2875 if (iter != mCameraStates.end()) {
2876 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 }
2878 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002879 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880}
2881
Ruben Brunkcc776712015-02-17 20:18:47 -08002882sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2883 // Remove from active clients list
2884 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2885 if (clientDescriptorPtr == nullptr) {
2886 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2887 cameraId.string());
2888 return sp<BasicClient>{nullptr};
2889 }
2890
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002891 sp<BasicClient> client = clientDescriptorPtr->getValue();
2892 if (client.get() != nullptr) {
2893 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2894 }
2895 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002896}
2897
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002898void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002899 // Acquire mServiceLock and prevent other clients from connecting
2900 std::unique_ptr<AutoConditionLock> lock =
2901 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2902
Ruben Brunk6267b532015-04-30 17:44:07 -07002903 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002904 for (size_t i = 0; i < newUserIds.size(); i++) {
2905 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002906 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002907 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002908 return;
2909 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002910 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002911 }
2912
Ruben Brunka8ca9152015-04-07 14:23:40 -07002913
Ruben Brunk6267b532015-04-30 17:44:07 -07002914 if (newAllowedUsers == mAllowedUsers) {
2915 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2916 return;
2917 }
2918
2919 logUserSwitch(mAllowedUsers, newAllowedUsers);
2920
2921 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002922
2923 // Current user has switched, evict all current clients.
2924 std::vector<sp<BasicClient>> evicted;
2925 for (auto& i : mActiveClientManager.getAll()) {
2926 auto clientSp = i->getValue();
2927
2928 if (clientSp.get() == nullptr) {
2929 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2930 continue;
2931 }
2932
Ruben Brunk6267b532015-04-30 17:44:07 -07002933 // Don't evict clients that are still allowed.
2934 uid_t clientUid = clientSp->getClientUid();
2935 userid_t clientUserId = multiuser_get_user_id(clientUid);
2936 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2937 continue;
2938 }
2939
Ruben Brunk36597b22015-03-20 22:15:57 -07002940 evicted.push_back(clientSp);
2941
2942 String8 curTime = getFormattedCurrentTime();
2943
2944 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2945 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002946
Ruben Brunk36597b22015-03-20 22:15:57 -07002947 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002948 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002949 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2950 " to user switch.", i->getKey().string(),
2951 String8{clientSp->getPackageName()}.string(),
2952 i->getOwnerId(), i->getPriority().getScore(),
2953 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002954
2955 }
2956
2957 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2958 // blocking other clients from connecting in mServiceLockWrapper if held.
2959 mServiceLock.unlock();
2960
2961 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002962 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002963
2964 for (auto& i : evicted) {
2965 i->disconnect();
2966 }
2967
Jayant Chowdhary12361932018-08-27 14:46:13 -07002968 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002969
2970 // Reacquire mServiceLock
2971 mServiceLock.lock();
2972}
Ruben Brunkcc776712015-02-17 20:18:47 -08002973
Ruben Brunka8ca9152015-04-07 14:23:40 -07002974void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002975 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002976 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002977 String8 msg = String8::format("%s : %s", curTime.string(), event);
2978 // For service error events, print the msg only once.
2979 if(!msg.contains("SERVICE ERROR")) {
2980 mEventLog.add(msg);
2981 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2982 // Error event not added to the dumpsys log before
2983 mEventLog.add(msg);
2984 sServiceErrorEventSet.insert(msg);
2985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986}
2987
Ruben Brunka8ca9152015-04-07 14:23:40 -07002988void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002989 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002990 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002991 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002992 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002993}
2994
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002995void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2996 const char* clientPackage) {
2997 // Log the clients evicted
2998 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2999 cameraId, clientPackage, clientPid));
3000}
3001
Ruben Brunka8ca9152015-04-07 14:23:40 -07003002void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003003 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003004 // Log the clients evicted
3005 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003006 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003007}
3008
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003009void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3010 const char* clientPackage) {
3011 // Log the clients evicted
3012 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3013 clientPackage, clientPid));
3014}
3015
Ruben Brunka8ca9152015-04-07 14:23:40 -07003016void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003017 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003018 // Log the client rejected
3019 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003020 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003021}
3022
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003023void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3024 // Log torch event
3025 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3026 torchState, clientPid));
3027}
3028
Ruben Brunk6267b532015-04-30 17:44:07 -07003029void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3030 const std::set<userid_t>& newUserIds) {
3031 String8 newUsers = toString(newUserIds);
3032 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003033 if (oldUsers.size() == 0) {
3034 oldUsers = "<None>";
3035 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003036 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003037 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003038 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003039}
3040
3041void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3042 // Log the device removal
3043 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3044}
3045
3046void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3047 // Log the device removal
3048 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3049}
3050
3051void CameraService::logClientDied(int clientPid, const char* reason) {
3052 // Log the device removal
3053 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003054}
3055
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003056void CameraService::logServiceError(const char* msg, int errorCode) {
3057 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003058 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003059}
3060
Ruben Brunk36597b22015-03-20 22:15:57 -07003061status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3062 uint32_t flags) {
3063
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 // Permission checks
3065 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003066 case SHELL_COMMAND_TRANSACTION: {
3067 int in = data.readFileDescriptor();
3068 int out = data.readFileDescriptor();
3069 int err = data.readFileDescriptor();
3070 int argc = data.readInt32();
3071 Vector<String16> args;
3072 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3073 args.add(data.readString16());
3074 }
3075 sp<IBinder> unusedCallback;
3076 sp<IResultReceiver> resultReceiver;
3077 status_t status;
3078 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3079 return status;
3080 }
3081 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3082 return status;
3083 }
3084 status = shellCommand(in, out, err, args);
3085 if (resultReceiver != nullptr) {
3086 resultReceiver->send(status);
3087 }
3088 return NO_ERROR;
3089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 }
3091
3092 return BnCameraService::onTransact(code, data, reply, flags);
3093}
3094
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095// We share the media players for shutter and recording sound for all clients.
3096// A reference count is kept to determine when we will actually release the
3097// media players.
3098
Jaekyun Seokef498052018-03-23 13:09:44 +09003099sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3100 sp<MediaPlayer> mp = new MediaPlayer();
3101 status_t error;
3102 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003103 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003104 error = mp->prepare();
3105 }
3106 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003107 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003108 mp->disconnect();
3109 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003110 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111 }
3112 return mp;
3113}
3114
username5755fea2018-12-27 09:48:08 +08003115void CameraService::increaseSoundRef() {
3116 Mutex::Autolock lock(mSoundLock);
3117 mSoundRef++;
3118}
3119
3120void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003121 ATRACE_CALL();
3122
username5755fea2018-12-27 09:48:08 +08003123 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3124 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3125 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3126 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3127 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3128 }
3129 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3130 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3131 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3132 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003133 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003134 }
3135 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3136 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3137 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3138 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3139 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003141}
3142
username5755fea2018-12-27 09:48:08 +08003143void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003145 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 if (--mSoundRef) return;
3147
3148 for (int i = 0; i < NUM_SOUNDS; i++) {
3149 if (mSoundPlayer[i] != 0) {
3150 mSoundPlayer[i]->disconnect();
3151 mSoundPlayer[i].clear();
3152 }
3153 }
3154}
3155
3156void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003157 ATRACE_CALL();
3158
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003160 if (kind < 0 || kind >= NUM_SOUNDS) {
3161 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3162 return;
3163 }
3164
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003166 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 sp<MediaPlayer> player = mSoundPlayer[kind];
3168 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003169 player->seekTo(0);
3170 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 }
3172}
3173
3174// ----------------------------------------------------------------------------
3175
3176CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003177 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003178 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003179 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003180 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003181 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003182 int clientPid, uid_t clientUid,
3183 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003184 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003185 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003186 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003187 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003188 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003189 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003190 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003191{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003192 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003193 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003195 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196
username5755fea2018-12-27 09:48:08 +08003197 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003198
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003199 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200}
3201
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202// tear down the client
3203CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003204 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003205 mDestructionStarted = true;
3206
username5755fea2018-12-27 09:48:08 +08003207 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003208 // unconditionally disconnect. function is idempotent
3209 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210}
3211
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003212sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3213
Igor Murashkin634a5152013-02-20 17:15:11 -08003214CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003215 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003216 const String16& clientPackageName, bool nativeClient,
3217 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3218 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003219 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003220 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003221 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003222 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3223 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003224 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003225 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003226 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003227 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003228 mRemoteBinder(remoteCallback),
3229 mOpsActive(false),
3230 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003231{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003232 if (sCameraService == nullptr) {
3233 sCameraService = cameraService;
3234 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003235
3236 // In some cases the calling code has no access to the package it runs under.
3237 // For example, NDK camera API.
3238 // In this case we will get the packages for the calling UID and pick the first one
3239 // for attributing the app op. This will work correctly for runtime permissions
3240 // as for legacy apps we will toggle the app op for all packages in the UID.
3241 // The caveat is that the operation may be attributed to the wrong package and
3242 // stats based on app ops may be slightly off.
3243 if (mClientPackageName.size() <= 0) {
3244 sp<IServiceManager> sm = defaultServiceManager();
3245 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3246 if (binder == 0) {
3247 ALOGE("Cannot get permission service");
3248 // Leave mClientPackageName unchanged (empty) and the further interaction
3249 // with camera will fail in BasicClient::startCameraOps
3250 return;
3251 }
3252
3253 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3254 Vector<String16> packages;
3255
3256 permCtrl->getPackagesForUid(mClientUid, packages);
3257
3258 if (packages.isEmpty()) {
3259 ALOGE("No packages for calling UID");
3260 // Leave mClientPackageName unchanged (empty) and the further interaction
3261 // with camera will fail in BasicClient::startCameraOps
3262 return;
3263 }
3264 mClientPackageName = packages[0];
3265 }
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003266
3267 // There are 2 scenarios in which a client won't have AppOps operations
3268 // (both scenarios : native clients)
3269 // 1) It's an system native client*, the package name will be empty
3270 // and it will return from this function in the previous if condition
3271 // (This is the same as the previously existing behavior).
3272 // 2) It is a system native client, but its package name has been
3273 // modified for debugging, however it still must not use AppOps since
3274 // the package name is not a real one.
3275 //
3276 // * system native client - native client with UID < AID_APP_START. It
3277 // doesn't exclude clients not on the system partition.
3278 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003279 mAppOpsManager = std::make_unique<AppOpsManager>();
3280 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003281
3282 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003283}
3284
3285CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003286 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003287 mDestructionStarted = true;
3288}
3289
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003290binder::Status CameraService::BasicClient::disconnect() {
3291 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003292 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003293 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003294 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003295 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003296
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003297 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003298 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003299 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3300 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003301
3302 sp<IBinder> remote = getRemote();
3303 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003304 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003305 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003306
3307 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003308 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003309 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3310 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3311 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003312
Igor Murashkincba2c162013-03-20 15:56:31 -07003313 // client shouldn't be able to call into us anymore
3314 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003315
3316 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003317}
3318
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003319status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3320 // No dumping of clients directly over Binder,
3321 // must go through CameraService::dump
3322 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003323 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003324 return OK;
3325}
3326
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003327status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3328 // Can't watch tags directly, must go through CameraService::startWatchingTags
3329 return OK;
3330}
3331
3332status_t CameraService::BasicClient::stopWatchingTags(int) {
3333 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3334 return OK;
3335}
3336
3337status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3338 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3339 return OK;
3340}
3341
Ruben Brunkcc776712015-02-17 20:18:47 -08003342String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003343 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003344}
3345
Emilian Peev8b64f282021-03-25 16:49:57 -07003346int CameraService::BasicClient::getCameraFacing() const {
3347 return mCameraFacing;
3348}
3349
3350int CameraService::BasicClient::getCameraOrientation() const {
3351 return mOrientation;
3352}
Ruben Brunkcc776712015-02-17 20:18:47 -08003353
3354int CameraService::BasicClient::getClientPid() const {
3355 return mClientPid;
3356}
3357
Ruben Brunk6267b532015-04-30 17:44:07 -07003358uid_t CameraService::BasicClient::getClientUid() const {
3359 return mClientUid;
3360}
3361
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003362bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3363 // Defaults to API2.
3364 return level == API_2;
3365}
3366
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003367status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003368 {
3369 Mutex::Autolock l(mAudioRestrictionLock);
3370 mAudioRestriction = mode;
3371 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003372 sCameraService->updateAudioRestriction();
3373 return OK;
3374}
3375
3376int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003377 return sCameraService->updateAudioRestriction();
3378}
3379
3380int32_t CameraService::BasicClient::getAudioRestriction() const {
3381 Mutex::Autolock l(mAudioRestrictionLock);
3382 return mAudioRestriction;
3383}
3384
3385bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3386 switch (mode) {
3387 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3388 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3389 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3390 return true;
3391 default:
3392 return false;
3393 }
3394}
3395
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003396status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3397 if (mode == AppOpsManager::MODE_ERRORED) {
3398 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3399 mCameraIdStr.string(), String8(mClientPackageName).string());
3400 return PERMISSION_DENIED;
3401 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3402 // If the calling Uid is trusted (a native service), the AppOpsManager could
3403 // return MODE_IGNORED. Do not treat such case as error.
3404 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3405 mClientPackageName);
3406 bool isCameraPrivacyEnabled =
3407 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3408 multiuser_get_user_id(mClientUid));
3409 if (!isUidActive || !isCameraPrivacyEnabled) {
3410 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3411 mCameraIdStr.string(), String8(mClientPackageName).string());
3412 // Return the same error as for device policy manager rejection
3413 return -EACCES;
3414 }
3415 }
3416 return OK;
3417}
3418
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003419status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003420 ATRACE_CALL();
3421
Igor Murashkine6800ce2013-03-04 17:25:57 -08003422 {
3423 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003424 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003425 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003426 if (mAppOpsManager != nullptr) {
3427 // Notify app ops that the camera is not available
3428 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003429 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3430 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003431
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003432 // Just check for camera acccess here on open - delay startOp until
3433 // camera frames start streaming in startCameraStreamingOps
3434 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3435 mClientPackageName);
3436 status_t res = handleAppOpMode(mode);
3437 if (res != OK) {
3438 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003439 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003440 }
3441
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003442 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003443
3444 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003445 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003446
Emilian Peev53722fa2019-02-22 17:47:20 -08003447 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3448
Shuzhen Wang695044d2020-03-06 09:02:23 -08003449 // Notify listeners of camera open/close status
3450 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3451
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003452 return OK;
3453}
3454
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003455status_t CameraService::BasicClient::startCameraStreamingOps() {
3456 ATRACE_CALL();
3457
3458 if (!mOpsActive) {
3459 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3460 return INVALID_OPERATION;
3461 }
3462 if (mOpsStreaming) {
3463 ALOGV("%s: Streaming already active!", __FUNCTION__);
3464 return OK;
3465 }
3466
3467 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3468 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3469
3470 if (mAppOpsManager != nullptr) {
3471 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3472 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3473 String16("start camera ") + String16(mCameraIdStr));
3474 status_t res = handleAppOpMode(mode);
3475 if (res != OK) {
3476 return res;
3477 }
3478 }
3479
3480 mOpsStreaming = true;
3481
3482 return OK;
3483}
3484
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003485status_t CameraService::BasicClient::noteAppOp() {
3486 ATRACE_CALL();
3487
3488 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3489 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3490
3491 // noteAppOp is only used for when camera mute is not supported, in order
3492 // to trigger the sensor privacy "Unblock" dialog
3493 if (mAppOpsManager != nullptr) {
3494 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3495 mClientPackageName, mClientFeatureId,
3496 String16("start camera ") + String16(mCameraIdStr));
3497 status_t res = handleAppOpMode(mode);
3498 if (res != OK) {
3499 return res;
3500 }
3501 }
3502
3503 return OK;
3504}
3505
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003506status_t CameraService::BasicClient::finishCameraStreamingOps() {
3507 ATRACE_CALL();
3508
3509 if (!mOpsActive) {
3510 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3511 return INVALID_OPERATION;
3512 }
3513 if (!mOpsStreaming) {
3514 ALOGV("%s: Streaming not active!", __FUNCTION__);
3515 return OK;
3516 }
3517
3518 if (mAppOpsManager != nullptr) {
3519 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3520 mClientPackageName, mClientFeatureId);
3521 mOpsStreaming = false;
3522 }
3523
3524 return OK;
3525}
3526
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003527status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003528 ATRACE_CALL();
3529
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003530 if (mOpsStreaming) {
3531 // Make sure we've notified everyone about camera stopping
3532 finishCameraStreamingOps();
3533 }
3534
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003535 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003536 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003537 mOpsActive = false;
3538
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003539 // This function is called when a client disconnects. This should
3540 // release the camera, but actually only if it was in a proper
3541 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003542 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003543 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003544
Ruben Brunkcc776712015-02-17 20:18:47 -08003545 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003546 sCameraService->updateStatus(StatusInternal::PRESENT,
3547 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003548 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003549 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003550 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3551 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003552 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003553 mOpsCallback.clear();
3554
Emilian Peev53722fa2019-02-22 17:47:20 -08003555 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3556
Shuzhen Wang695044d2020-03-06 09:02:23 -08003557 // Notify listeners of camera open/close status
3558 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3559
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003560 return OK;
3561}
3562
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003563void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003564 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003565 if (mAppOpsManager == nullptr) {
3566 return;
3567 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003568 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003569 if (op != AppOpsManager::OP_CAMERA) {
3570 ALOGW("Unexpected app ops notification received: %d", op);
3571 return;
3572 }
3573
3574 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003575 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003576 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003577 ALOGV("checkOp returns: %d, %s ", res,
3578 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3579 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3580 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3581 "UNKNOWN");
3582
Shuzhen Wang64900852021-02-05 09:03:29 -08003583 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003584 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003585 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003586 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003587 } else if (res == AppOpsManager::MODE_IGNORED) {
3588 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003589 bool isCameraPrivacyEnabled =
3590 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3591 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003592 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3593 mCameraIdStr.string(), String8(mClientPackageName).string(),
3594 mUidIsTrusted, isUidActive);
3595 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3596 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3597 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003598 if (!mUidIsTrusted) {
3599 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3600 setCameraMute(true);
3601 } else if (!isUidActive
3602 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3603 block();
3604 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003605 }
Evan Severson09ab4002021-02-10 14:15:19 -08003606 } else if (res == AppOpsManager::MODE_ALLOWED) {
3607 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003608 }
3609}
3610
Svet Ganova453d0d2018-01-11 15:37:58 -08003611void CameraService::BasicClient::block() {
3612 ATRACE_CALL();
3613
3614 // Reset the client PID to allow server-initiated disconnect,
3615 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003616 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003617 CaptureResultExtras resultExtras; // a dummy result (invalid)
3618 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3619 disconnect();
3620}
3621
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622// ----------------------------------------------------------------------------
3623
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003624void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003625 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003626 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003627 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003628 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3629 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3630 api1ErrorCode = CAMERA_ERROR_DISABLED;
3631 }
3632 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003633 } else {
3634 ALOGE("mRemoteCallback is NULL!!");
3635 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003636}
3637
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003638// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003639binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003640 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003641 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003642}
3643
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003644bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3645 return level == API_1;
3646}
3647
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003648CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3649 mClient(client) {
3650}
3651
3652void CameraService::Client::OpsCallback::opChanged(int32_t op,
3653 const String16& packageName) {
3654 sp<BasicClient> client = mClient.promote();
3655 if (client != NULL) {
3656 client->opChanged(op, packageName);
3657 }
3658}
3659
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003661// UidPolicy
3662// ----------------------------------------------------------------------------
3663
3664void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003665 Mutex::Autolock _l(mUidLock);
3666
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003667 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003668 status_t res = mAm.linkToDeath(this);
3669 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003670 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003671 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003672 ActivityManager::PROCESS_STATE_UNKNOWN,
3673 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003674 if (res == OK) {
3675 mRegistered = true;
3676 ALOGV("UidPolicy: Registered with ActivityManager");
3677 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003678}
3679
3680void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003681 Mutex::Autolock _l(mUidLock);
3682
Steven Moreland2f348142019-07-02 15:59:07 -07003683 mAm.unregisterUidObserver(this);
3684 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003685 mRegistered = false;
3686 mActiveUids.clear();
3687 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003688}
3689
3690void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3691 onUidIdle(uid, disabled);
3692}
3693
3694void CameraService::UidPolicy::onUidActive(uid_t uid) {
3695 Mutex::Autolock _l(mUidLock);
3696 mActiveUids.insert(uid);
3697}
3698
3699void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3700 bool deleted = false;
3701 {
3702 Mutex::Autolock _l(mUidLock);
3703 if (mActiveUids.erase(uid) > 0) {
3704 deleted = true;
3705 }
3706 }
3707 if (deleted) {
3708 sp<CameraService> service = mService.promote();
3709 if (service != nullptr) {
3710 service->blockClientsForUid(uid);
3711 }
3712 }
3713}
3714
Emilian Peev53722fa2019-02-22 17:47:20 -08003715void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003716 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003717 bool procStateChange = false;
3718 {
3719 Mutex::Autolock _l(mUidLock);
3720 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3721 (mMonitoredUids[uid].first != procState)) {
3722 mMonitoredUids[uid].first = procState;
3723 procStateChange = true;
3724 }
3725 }
3726
3727 if (procStateChange) {
3728 sp<CameraService> service = mService.promote();
3729 if (service != nullptr) {
3730 service->notifyMonitoredUids();
3731 }
3732 }
3733}
3734
3735void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3736 Mutex::Autolock _l(mUidLock);
3737 auto it = mMonitoredUids.find(uid);
3738 if (it != mMonitoredUids.end()) {
3739 it->second.second++;
3740 } else {
3741 mMonitoredUids.emplace(
3742 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3743 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3744 }
3745}
3746
3747void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3748 Mutex::Autolock _l(mUidLock);
3749 auto it = mMonitoredUids.find(uid);
3750 if (it != mMonitoredUids.end()) {
3751 it->second.second--;
3752 if (it->second.second == 0) {
3753 mMonitoredUids.erase(it);
3754 }
3755 } else {
3756 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3757 }
3758}
3759
Svet Ganov7b4ab782018-03-25 12:48:10 -07003760bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003761 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003762 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003763}
3764
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003765static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3766static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003767
Svet Ganov7b4ab782018-03-25 12:48:10 -07003768bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003769 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003770 // If activity manager is unreachable, assume everything is active
3771 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003772 return true;
3773 }
3774 auto it = mOverrideUids.find(uid);
3775 if (it != mOverrideUids.end()) {
3776 return it->second;
3777 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003778 bool active = mActiveUids.find(uid) != mActiveUids.end();
3779 if (!active) {
3780 // We want active UIDs to always access camera with their first attempt since
3781 // there is no guarantee the app is robustly written and would retry getting
3782 // the camera on failure. The inverse case is not a problem as we would take
3783 // camera away soon once we get the callback that the uid is no longer active.
3784 ActivityManager am;
3785 // Okay to access with a lock held as UID changes are dispatched without
3786 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003787 int64_t startTimeMillis = 0;
3788 do {
3789 // TODO: Fix this b/109950150!
3790 // Okay this is a hack. There is a race between the UID turning active and
3791 // activity being resumed. The proper fix is very risky, so we temporary add
3792 // some polling which should happen pretty rarely anyway as the race is hard
3793 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003794 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003795 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003796 if (active) {
3797 break;
3798 }
3799 if (startTimeMillis <= 0) {
3800 startTimeMillis = uptimeMillis();
3801 }
3802 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003803 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003804 if (remainingTimeMillis <= 0) {
3805 break;
3806 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003807 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3808
3809 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003810 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003811 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003812 } while (true);
3813
Svet Ganov7b4ab782018-03-25 12:48:10 -07003814 if (active) {
3815 // Now that we found out the UID is actually active, cache that
3816 mActiveUids.insert(uid);
3817 }
3818 }
3819 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003820}
3821
Varun Shahb42f1eb2019-04-16 14:45:13 -07003822int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3823 Mutex::Autolock _l(mUidLock);
3824 return getProcStateLocked(uid);
3825}
3826
3827int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3828 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3829 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3830 procState = mMonitoredUids[uid].first;
3831 }
3832 return procState;
3833}
3834
Svet Ganov7b4ab782018-03-25 12:48:10 -07003835void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3836 String16 callingPackage, bool active) {
3837 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003838}
3839
Svet Ganov7b4ab782018-03-25 12:48:10 -07003840void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3841 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003842}
3843
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003844void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3845 Mutex::Autolock _l(mUidLock);
3846 ALOGV("UidPolicy: ActivityManager has died");
3847 mRegistered = false;
3848 mActiveUids.clear();
3849}
3850
Svet Ganov7b4ab782018-03-25 12:48:10 -07003851void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3852 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003853 bool wasActive = false;
3854 bool isActive = false;
3855 {
3856 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003857 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003858 mOverrideUids.erase(uid);
3859 if (insert) {
3860 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3861 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003862 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003863 }
3864 if (wasActive != isActive && !isActive) {
3865 sp<CameraService> service = mService.promote();
3866 if (service != nullptr) {
3867 service->blockClientsForUid(uid);
3868 }
3869 }
3870}
3871
3872// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003873// SensorPrivacyPolicy
3874// ----------------------------------------------------------------------------
3875void CameraService::SensorPrivacyPolicy::registerSelf() {
3876 Mutex::Autolock _l(mSensorPrivacyLock);
3877 if (mRegistered) {
3878 return;
3879 }
Evan Severson09ab4002021-02-10 14:15:19 -08003880 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003881 mSpm.addSensorPrivacyListener(this);
3882 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3883 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003884 if (res == OK) {
3885 mRegistered = true;
3886 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3887 }
3888}
3889
3890void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3891 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003892 mSpm.removeSensorPrivacyListener(this);
3893 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003894 mRegistered = false;
3895 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3896}
3897
3898bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3899 Mutex::Autolock _l(mSensorPrivacyLock);
3900 return mSensorPrivacyEnabled;
3901}
3902
Evan Severson09ab4002021-02-10 14:15:19 -08003903bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3904 if (!hasCameraPrivacyFeature()) {
3905 return false;
3906 }
3907 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3908 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3909}
3910
Michael Grooverd1d435a2018-12-18 17:39:42 -08003911binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3912 {
3913 Mutex::Autolock _l(mSensorPrivacyLock);
3914 mSensorPrivacyEnabled = enabled;
3915 }
3916 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003917 if (enabled) {
3918 sp<CameraService> service = mService.promote();
3919 if (service != nullptr) {
3920 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003921 }
3922 }
3923 return binder::Status::ok();
3924}
3925
3926void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3927 Mutex::Autolock _l(mSensorPrivacyLock);
3928 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3929 mRegistered = false;
3930}
3931
Evan Severson09ab4002021-02-10 14:15:19 -08003932bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003933 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003934}
3935
Michael Grooverd1d435a2018-12-18 17:39:42 -08003936// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003937// CameraState
3938// ----------------------------------------------------------------------------
3939
3940CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003941 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
3942 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003943 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003944 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003945
3946CameraService::CameraState::~CameraState() {}
3947
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003948CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003949 Mutex::Autolock lock(mStatusLock);
3950 return mStatus;
3951}
3952
Shuzhen Wang43858162020-01-10 13:42:15 -08003953std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3954 Mutex::Autolock lock(mStatusLock);
3955 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3956 return res;
3957}
3958
Ruben Brunkcc776712015-02-17 20:18:47 -08003959CameraParameters CameraService::CameraState::getShimParams() const {
3960 return mShimParams;
3961}
3962
3963void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3964 mShimParams = params;
3965}
3966
3967int CameraService::CameraState::getCost() const {
3968 return mCost;
3969}
3970
3971std::set<String8> CameraService::CameraState::getConflicting() const {
3972 return mConflicting;
3973}
3974
3975String8 CameraService::CameraState::getId() const {
3976 return mId;
3977}
3978
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003979SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3980 return mSystemCameraKind;
3981}
3982
Shuzhen Wang403af6d2021-12-21 00:08:43 +00003983bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
3984 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
3985 != mPhysicalCameras.end();
3986}
3987
Shuzhen Wang43858162020-01-10 13:42:15 -08003988bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3989 Mutex::Autolock lock(mStatusLock);
3990 auto result = mUnavailablePhysicalIds.insert(physicalId);
3991 return result.second;
3992}
3993
3994bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3995 Mutex::Autolock lock(mStatusLock);
3996 auto count = mUnavailablePhysicalIds.erase(physicalId);
3997 return count > 0;
3998}
3999
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004000void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4001 Mutex::Autolock lock(mStatusLock);
4002 mClientPackage = clientPackage;
4003}
4004
4005String8 CameraService::CameraState::getClientPackage() const {
4006 Mutex::Autolock lock(mStatusLock);
4007 return mClientPackage;
4008}
4009
Ruben Brunkcc776712015-02-17 20:18:47 -08004010// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004011// ClientEventListener
4012// ----------------------------------------------------------------------------
4013
4014void CameraService::ClientEventListener::onClientAdded(
4015 const resource_policy::ClientDescriptor<String8,
4016 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004017 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004018 if (basicClient.get() != nullptr) {
4019 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4020 notifier.noteStartCamera(descriptor.getKey(),
4021 static_cast<int>(basicClient->getClientUid()));
4022 }
4023}
4024
4025void CameraService::ClientEventListener::onClientRemoved(
4026 const resource_policy::ClientDescriptor<String8,
4027 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004028 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004029 if (basicClient.get() != nullptr) {
4030 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4031 notifier.noteStopCamera(descriptor.getKey(),
4032 static_cast<int>(basicClient->getClientUid()));
4033 }
4034}
4035
4036
4037// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004038// CameraClientManager
4039// ----------------------------------------------------------------------------
4040
Ruben Brunk99e69712015-05-26 17:25:07 -07004041CameraService::CameraClientManager::CameraClientManager() {
4042 setListener(std::make_shared<ClientEventListener>());
4043}
4044
Ruben Brunkcc776712015-02-17 20:18:47 -08004045CameraService::CameraClientManager::~CameraClientManager() {}
4046
4047sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4048 const String8& id) const {
4049 auto descriptor = get(id);
4050 if (descriptor == nullptr) {
4051 return sp<BasicClient>{nullptr};
4052 }
4053 return descriptor->getValue();
4054}
4055
4056String8 CameraService::CameraClientManager::toString() const {
4057 auto all = getAll();
4058 String8 ret("[");
4059 bool hasAny = false;
4060 for (auto& i : all) {
4061 hasAny = true;
4062 String8 key = i->getKey();
4063 int32_t cost = i->getCost();
4064 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004065 int32_t score = i->getPriority().getScore();
4066 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004067 auto conflicting = i->getConflicting();
4068 auto clientSp = i->getValue();
4069 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004070 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004071 if (clientSp.get() != nullptr) {
4072 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004073 uid_t clientUid = clientSp->getClientUid();
4074 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004075 }
Emilian Peev8131a262017-02-01 12:33:43 +00004076 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4077 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004078
Ruben Brunk6267b532015-04-30 17:44:07 -07004079 if (clientSp.get() != nullptr) {
4080 ret.appendFormat("User Id: %d, ", clientUserId);
4081 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004082 if (packageName.size() != 0) {
4083 ret.appendFormat("Client Package Name: %s", packageName.string());
4084 }
4085
4086 ret.append(", Conflicting Client Devices: {");
4087 for (auto& j : conflicting) {
4088 ret.appendFormat("%s, ", j.string());
4089 }
4090 ret.append("})");
4091 }
4092 if (hasAny) ret.append("\n");
4093 ret.append("]\n");
4094 return ret;
4095}
4096
4097CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4098 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004099 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004100 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004101
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004102 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4103 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004104
Ruben Brunkcc776712015-02-17 20:18:47 -08004105 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004106 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4107 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004108}
4109
4110CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004111 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004112 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004113 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004114 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004115 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4116 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004117}
4118
4119// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004120// InjectionStatusListener
4121// ----------------------------------------------------------------------------
4122
4123void CameraService::InjectionStatusListener::addListener(
4124 const sp<ICameraInjectionCallback>& callback) {
4125 Mutex::Autolock lock(mListenerLock);
4126 if (mCameraInjectionCallback) return;
4127 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4128 if (res == OK) {
4129 mCameraInjectionCallback = callback;
4130 }
4131}
4132
4133void CameraService::InjectionStatusListener::removeListener() {
4134 Mutex::Autolock lock(mListenerLock);
4135 if (mCameraInjectionCallback == nullptr) {
4136 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4137 return;
4138 }
4139 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4140 mCameraInjectionCallback = nullptr;
4141}
4142
4143void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004144 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004145 if (mCameraInjectionCallback == nullptr) {
4146 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4147 return;
4148 }
Cliff Wud3a05312021-04-26 23:07:31 +08004149
4150 switch (err) {
4151 case -ENODEV:
4152 mCameraInjectionCallback->onInjectionError(
4153 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4154 ALOGE("No camera device with ID \"%s\" currently available!",
4155 injectedCamId.string());
4156 break;
4157 case -EBUSY:
4158 mCameraInjectionCallback->onInjectionError(
4159 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4160 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4161 injectedCamId.string());
4162 break;
4163 case DEAD_OBJECT:
4164 mCameraInjectionCallback->onInjectionError(
4165 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4166 ALOGE("Camera ID \"%s\" object is dead!",
4167 injectedCamId.string());
4168 break;
4169 case INVALID_OPERATION:
4170 mCameraInjectionCallback->onInjectionError(
4171 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4172 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4173 injectedCamId.string());
4174 break;
4175 case UNKNOWN_TRANSACTION:
4176 mCameraInjectionCallback->onInjectionError(
4177 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4178 ALOGE("Camera ID \"%s\" method doesn't support!",
4179 injectedCamId.string());
4180 break;
4181 default:
4182 mCameraInjectionCallback->onInjectionError(
4183 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4184 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4185 strerror(-err), err, injectedCamId.string());
4186 }
Cliff Wud8cae102021-03-11 01:37:42 +08004187}
4188
4189void CameraService::InjectionStatusListener::binderDied(
4190 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004191 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4192 auto parent = mParent.promote();
4193 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004194 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4195 if (clientDescriptor != nullptr) {
4196 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4197 baseClientPtr->stopInjection();
4198 }
Cliff Wu3b268182021-07-06 15:44:43 +08004199 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004200 }
4201}
4202
4203// ----------------------------------------------------------------------------
4204// CameraInjectionSession
4205// ----------------------------------------------------------------------------
4206
4207binder::Status CameraService::CameraInjectionSession::stopInjection() {
4208 Mutex::Autolock lock(mInjectionSessionLock);
4209 auto parent = mParent.promote();
4210 if (parent == nullptr) {
4211 ALOGE("CameraInjectionSession: Parent is gone");
4212 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4213 "Camera service encountered error");
4214 }
Cliff Wud3a05312021-04-26 23:07:31 +08004215
4216 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004217 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4218 if (clientDescriptor != nullptr) {
4219 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4220 res = baseClientPtr->stopInjection();
4221 if (res != OK) {
4222 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4223 " ret != NO_ERROR: %d", res);
4224 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4225 "Camera session encountered error");
4226 }
4227 }
Cliff Wu3b268182021-07-06 15:44:43 +08004228 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004229 return binder::Status::ok();
4230}
4231
4232// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233
4234static const int kDumpLockRetries = 50;
4235static const int kDumpLockSleep = 60000;
4236
4237static bool tryLock(Mutex& mutex)
4238{
4239 bool locked = false;
4240 for (int i = 0; i < kDumpLockRetries; ++i) {
4241 if (mutex.tryLock() == NO_ERROR) {
4242 locked = true;
4243 break;
4244 }
4245 usleep(kDumpLockSleep);
4246 }
4247 return locked;
4248}
4249
Rucha Katakwardf223072021-06-15 10:21:00 -07004250void CameraService::cacheDump() {
4251 if (mMemFd != -1) {
4252 const Vector<String16> args;
4253 ATRACE_CALL();
4254 // Acquiring service lock here will avoid the deadlock since
4255 // cacheDump will not be called during the second disconnect.
4256 Mutex::Autolock lock(mServiceLock);
4257
4258 Mutex::Autolock l(mCameraStatesLock);
4259 // Start collecting the info for open sessions and store it in temp file.
4260 for (const auto& state : mCameraStates) {
4261 String8 cameraId = state.first;
4262 auto clientDescriptor = mActiveClientManager.get(cameraId);
4263 if (clientDescriptor != nullptr) {
4264 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4265 // Log the current open session info before device is disconnected.
4266 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4267 }
4268 }
4269 }
4270}
4271
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004273 ATRACE_CALL();
4274
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004275 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004276 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004277 CameraThreadState::getCallingPid(),
4278 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004279 return NO_ERROR;
4280 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004281 bool locked = tryLock(mServiceLock);
4282 // failed to lock - CameraService is probably deadlocked
4283 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004284 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004285 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004286
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004287 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004288 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004289
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004290 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004291 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004292
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004293 if (locked) mServiceLock.unlock();
4294 return NO_ERROR;
4295 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004296 dprintf(fd, "\n== Service global info: ==\n\n");
4297 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004298 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004299 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4300 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004301 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4302 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4303 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004304 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004305 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4306 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004307
4308 dumpEventLog(fd);
4309
4310 bool stateLocked = tryLock(mCameraStatesLock);
4311 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004312 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004313 }
4314
Emilian Peevbd8c5032018-02-14 23:05:40 +00004315 int argSize = args.size();
4316 for (int i = 0; i < argSize; i++) {
4317 if (args[i] == TagMonitor::kMonitorOption) {
4318 if (i + 1 < argSize) {
4319 mMonitorTags = String8(args[i + 1]);
4320 }
4321 break;
4322 }
4323 }
4324
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004325 for (auto& state : mCameraStates) {
4326 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004327
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004328 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004329
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004330 CameraParameters p = state.second->getShimParams();
4331 if (!p.isEmpty()) {
4332 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4333 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004334 }
4335
4336 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004337 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004338 // log the current open session info
4339 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004340 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004341 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004342 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004343
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004344 }
4345
4346 if (stateLocked) mCameraStatesLock.unlock();
4347
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004348 if (locked) mServiceLock.unlock();
4349
Emilian Peevf53f66e2017-04-11 14:29:43 +01004350 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004351
4352 dprintf(fd, "\n== Vendor tags: ==\n\n");
4353
4354 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4355 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004356 sp<VendorTagDescriptorCache> cache =
4357 VendorTagDescriptorCache::getGlobalVendorTagCache();
4358 if (cache == NULL) {
4359 dprintf(fd, "No vendor tags.\n");
4360 } else {
4361 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4362 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004363 } else {
4364 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4365 }
4366
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004367 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004368 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004369 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004370
4371 // Process dump arguments, if any
4372 int n = args.size();
4373 String16 verboseOption("-v");
4374 String16 unreachableOption("--unreachable");
4375 for (int i = 0; i < n; i++) {
4376 if (args[i] == verboseOption) {
4377 // change logging level
4378 if (i + 1 >= n) continue;
4379 String8 levelStr(args[i+1]);
4380 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004381 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004382 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004383 } else if (args[i] == unreachableOption) {
4384 // Dump memory analysis
4385 // TODO - should limit be an argument parameter?
4386 UnreachableMemoryInfo info;
4387 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4388 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004389 dprintf(fd, "\n== Unable to dump unreachable memory. "
4390 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004391 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004392 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004393 std::string s = info.ToString(/*log_contents*/ true);
4394 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 }
4396 }
4397 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004398
4399 bool serviceLocked = tryLock(mServiceLock);
4400
4401 // Dump info from previous open sessions.
4402 // Reposition the offset to beginning of the file before reading
4403
4404 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4405 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4406 ssize_t size_read;
4407 char buf[4096];
4408 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4409 // Read data from file to a small buffer and write it to fd.
4410 write(fd, buf, size_read);
4411 if (size_read == -1) {
4412 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4413 break;
4414 }
4415 }
4416 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4417 } else {
4418 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4419 }
4420
4421 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 return NO_ERROR;
4423}
4424
Rucha Katakwardf223072021-06-15 10:21:00 -07004425void CameraService::dumpOpenSessionClientLogs(int fd,
4426 const Vector<String16>& args, const String8& cameraId) {
4427 auto clientDescriptor = mActiveClientManager.get(cameraId);
4428 dprintf(fd, " Device %s is open. Client instance dump:\n",
4429 cameraId.string());
4430 dprintf(fd, " Client priority score: %d state: %d\n",
4431 clientDescriptor->getPriority().getScore(),
4432 clientDescriptor->getPriority().getState());
4433 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4434
4435 auto client = clientDescriptor->getValue();
4436 dprintf(fd, " Client package: %s\n",
4437 String8(client->getPackageName()).string());
4438
4439 client->dumpClient(fd, args);
4440}
4441
4442void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4443 dprintf(fd, " Device %s is closed, no client instance\n",
4444 cameraId.string());
4445}
4446
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004447void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004448 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004449
4450 Mutex::Autolock l(mLogLock);
4451 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004452 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004453 }
4454
4455 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004456 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004457 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004458 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004459 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004460 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004461}
4462
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004463void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4464 Mutex::Autolock lock(mLogLock);
4465 if (!isClientWatchedLocked(client)) { return; }
4466
4467 std::vector<std::string> dumpVector;
4468 client->dumpWatchedEventsToVector(dumpVector);
4469
4470 if (dumpVector.empty()) { return; }
4471
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004472 std::string dumpString;
4473
4474 String8 currentTime = getFormattedCurrentTime();
4475 dumpString += "Cached @ ";
4476 dumpString += currentTime.string();
4477 dumpString += "\n"; // First line is the timestamp of when client is cached.
4478
4479
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004480 const String16 &packageName = client->getPackageName();
4481
4482 String8 packageName8 = String8(packageName);
4483 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4484
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004485
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004486 size_t i = dumpVector.size();
4487
4488 // Store the string in reverse order (latest last)
4489 while (i > 0) {
4490 i--;
4491 dumpString += cameraId;
4492 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004493 dumpString += printablePackageName;
4494 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004495 dumpString += dumpVector[i]; // implicitly ends with '\n'
4496 }
4497
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004498 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004499 mWatchedClientsDumpCache[packageName] = dumpString;
4500}
4501
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004502void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004503 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004504 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4505 if (mTorchClientMap[i] == who) {
4506 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004507 String8 cameraId = mTorchClientMap.keyAt(i);
4508 status_t res = mFlashlight->setTorchMode(cameraId, false);
4509 if (res) {
4510 ALOGE("%s: torch client died but couldn't turn off torch: "
4511 "%s (%d)", __FUNCTION__, strerror(-res), res);
4512 return;
4513 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004514 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004515 break;
4516 }
4517 }
4518}
4519
Ruben Brunkcc776712015-02-17 20:18:47 -08004520/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004521
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004522 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004523 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4524 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004525 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004526 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004527 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004528
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004529 // check torch client
4530 handleTorchClientBinderDied(who);
4531
4532 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004533 if(!evictClientIdByRemote(who)) {
4534 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004535 return;
4536 }
4537
Ruben Brunkcc776712015-02-17 20:18:47 -08004538 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4539 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004540}
4541
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004542void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004543 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004544}
4545
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004546void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4547 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004548 // Do not lock mServiceLock here or can get into a deadlock from
4549 // connect() -> disconnect -> updateStatus
4550
4551 auto state = getCameraState(cameraId);
4552
4553 if (state == nullptr) {
4554 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4555 cameraId.string());
4556 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004557 }
4558
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004559 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4560 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4561 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4562 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4563 return;
4564 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004565
4566 // Collect the logical cameras without holding mStatusLock in updateStatus
4567 // as that can lead to a deadlock(b/162192331).
4568 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004569 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004570 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004571 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004572 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004573 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004574
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004575 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004576 // Update torch status if it has a flash unit.
4577 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004578 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004579 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4580 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004581 TorchModeStatus newTorchStatus =
4582 status == StatusInternal::PRESENT ?
4583 TorchModeStatus::AVAILABLE_OFF :
4584 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004585 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004586 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004587 }
4588 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004589 }
4590
4591 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004592 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4593 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004594
Ruben Brunkcc776712015-02-17 20:18:47 -08004595 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004596 bool isVendorListener = listener->isVendorListener();
4597 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4598 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004599 isVendorListener) {
4600 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004601 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004602 continue;
4603 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004604 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004605 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004606 }
4607 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004608}
4609
Shuzhen Wang695044d2020-03-06 09:02:23 -08004610void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4611 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004612 auto state = getCameraState(cameraId);
4613 if (state == nullptr) {
4614 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4615 cameraId.string());
4616 return;
4617 }
4618 if (open) {
4619 state->setClientPackage(String8(clientPackageName));
4620 } else {
4621 state->setClientPackage(String8::empty());
4622 }
4623
Shuzhen Wang695044d2020-03-06 09:02:23 -08004624 Mutex::Autolock lock(mStatusListenerLock);
4625
4626 for (const auto& it : mListenerList) {
4627 if (!it->isOpenCloseCallbackAllowed()) {
4628 continue;
4629 }
4630
4631 binder::Status ret;
4632 String16 cameraId64(cameraId);
4633 if (open) {
4634 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4635 } else {
4636 ret = it->getListener()->onCameraClosed(cameraId64);
4637 }
4638 if (!ret.isOk()) {
4639 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4640 ret.exceptionCode());
4641 }
4642 }
4643}
4644
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004645template<class Func>
4646void CameraService::CameraState::updateStatus(StatusInternal status,
4647 const String8& cameraId,
4648 std::initializer_list<StatusInternal> rejectSourceStates,
4649 Func onStatusUpdatedLocked) {
4650 Mutex::Autolock lock(mStatusLock);
4651 StatusInternal oldStatus = mStatus;
4652 mStatus = status;
4653
4654 if (oldStatus == status) {
4655 return;
4656 }
4657
4658 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4659 cameraId.string(), oldStatus, status);
4660
4661 if (oldStatus == StatusInternal::NOT_PRESENT &&
4662 (status != StatusInternal::PRESENT &&
4663 status != StatusInternal::ENUMERATING)) {
4664
4665 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4666 __FUNCTION__);
4667 mStatus = oldStatus;
4668 return;
4669 }
4670
4671 /**
4672 * Sometimes we want to conditionally do a transition.
4673 * For example if a client disconnects, we want to go to PRESENT
4674 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4675 */
4676 for (auto& rejectStatus : rejectSourceStates) {
4677 if (oldStatus == rejectStatus) {
4678 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4679 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4680 mStatus = oldStatus;
4681 return;
4682 }
4683 }
4684
4685 onStatusUpdatedLocked(cameraId, status);
4686}
4687
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004688status_t CameraService::getTorchStatusLocked(
4689 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004690 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004691 if (!status) {
4692 return BAD_VALUE;
4693 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004694 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4695 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004696 // invalid camera ID or the camera doesn't have a flash unit
4697 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004698 }
4699
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004700 *status = mTorchStatusMap.valueAt(index);
4701 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004702}
4703
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004704status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004705 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004706 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4707 if (index == NAME_NOT_FOUND) {
4708 return BAD_VALUE;
4709 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004710 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004711
4712 return OK;
4713}
4714
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004715std::list<String16> CameraService::getLogicalCameras(
4716 const String8& physicalCameraId) {
4717 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004718 Mutex::Autolock lock(mCameraStatesLock);
4719 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004720 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4721 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004722 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004723 }
4724 return retList;
4725}
4726
4727void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4728 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4729 SystemCameraKind deviceKind) {
4730 // mStatusListenerLock is expected to be locked
4731 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004732 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004733 // Note: we check only the deviceKind of the physical camera id
4734 // since, logical camera ids and their physical camera ids are
4735 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004736 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4737 listener->getListenerPid(), listener->getListenerUid())) {
4738 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004739 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004740 continue;
4741 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004742 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004743 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004744 }
4745 }
4746}
4747
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004748
Svet Ganova453d0d2018-01-11 15:37:58 -08004749void CameraService::blockClientsForUid(uid_t uid) {
4750 const auto clients = mActiveClientManager.getAll();
4751 for (auto& current : clients) {
4752 if (current != nullptr) {
4753 const auto basicClient = current->getValue();
4754 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4755 basicClient->block();
4756 }
4757 }
4758 }
4759}
4760
Michael Grooverd1d435a2018-12-18 17:39:42 -08004761void CameraService::blockAllClients() {
4762 const auto clients = mActiveClientManager.getAll();
4763 for (auto& current : clients) {
4764 if (current != nullptr) {
4765 const auto basicClient = current->getValue();
4766 if (basicClient.get() != nullptr) {
4767 basicClient->block();
4768 }
4769 }
4770 }
4771}
4772
Svet Ganova453d0d2018-01-11 15:37:58 -08004773// NOTE: This is a remote API - make sure all args are validated
4774status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4775 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4776 return PERMISSION_DENIED;
4777 }
4778 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4779 return BAD_VALUE;
4780 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004781 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004782 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004783 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004784 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004785 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004786 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004787 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4788 return handleSetRotateAndCrop(args);
4789 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4790 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004791 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4792 return handleSetImageDumpMask(args);
4793 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4794 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004795 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4796 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004797 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004798 return handleWatchCommand(args, in, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004799 } else if (args.size() == 1 && args[0] == String16("help")) {
4800 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004801 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004802 }
4803 printHelp(err);
4804 return BAD_VALUE;
4805}
4806
4807status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004808 String16 packageName = args[1];
4809
Svet Ganova453d0d2018-01-11 15:37:58 -08004810 bool active = false;
4811 if (args[2] == String16("active")) {
4812 active = true;
4813 } else if ((args[2] != String16("idle"))) {
4814 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4815 return BAD_VALUE;
4816 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004817
4818 int userId = 0;
4819 if (args.size() >= 5 && args[3] == String16("--user")) {
4820 userId = atoi(String8(args[4]));
4821 }
4822
4823 uid_t uid;
4824 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4825 return BAD_VALUE;
4826 }
4827
4828 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004829 return NO_ERROR;
4830}
4831
4832status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004833 String16 packageName = args[1];
4834
4835 int userId = 0;
4836 if (args.size() >= 4 && args[2] == String16("--user")) {
4837 userId = atoi(String8(args[3]));
4838 }
4839
4840 uid_t uid;
4841 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004842 return BAD_VALUE;
4843 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004844
4845 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004846 return NO_ERROR;
4847}
4848
4849status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004850 String16 packageName = args[1];
4851
4852 int userId = 0;
4853 if (args.size() >= 4 && args[2] == String16("--user")) {
4854 userId = atoi(String8(args[3]));
4855 }
4856
4857 uid_t uid;
4858 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004859 return BAD_VALUE;
4860 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004861
4862 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004863 return dprintf(out, "active\n");
4864 } else {
4865 return dprintf(out, "idle\n");
4866 }
4867}
4868
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004869status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4870 int rotateValue = atoi(String8(args[1]));
4871 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4872 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4873 Mutex::Autolock lock(mServiceLock);
4874
4875 mOverrideRotateAndCropMode = rotateValue;
4876
4877 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4878
4879 const auto clients = mActiveClientManager.getAll();
4880 for (auto& current : clients) {
4881 if (current != nullptr) {
4882 const auto basicClient = current->getValue();
4883 if (basicClient.get() != nullptr) {
4884 basicClient->setRotateAndCropOverride(rotateValue);
4885 }
4886 }
4887 }
4888
4889 return OK;
4890}
4891
4892status_t CameraService::handleGetRotateAndCrop(int out) {
4893 Mutex::Autolock lock(mServiceLock);
4894
4895 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4896}
4897
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004898status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4899 char *endPtr;
4900 errno = 0;
4901 String8 maskString8 = String8(args[1]);
4902 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4903
4904 if (errno != 0) return BAD_VALUE;
4905 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4906 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4907
4908 Mutex::Autolock lock(mServiceLock);
4909
4910 mImageDumpMask = maskValue;
4911
4912 return OK;
4913}
4914
4915status_t CameraService::handleGetImageDumpMask(int out) {
4916 Mutex::Autolock lock(mServiceLock);
4917
4918 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4919}
4920
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004921status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4922 int muteValue = strtol(String8(args[1]), nullptr, 10);
4923 if (errno != 0) return BAD_VALUE;
4924
4925 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4926 Mutex::Autolock lock(mServiceLock);
4927
4928 mOverrideCameraMuteMode = (muteValue == 1);
4929
4930 const auto clients = mActiveClientManager.getAll();
4931 for (auto& current : clients) {
4932 if (current != nullptr) {
4933 const auto basicClient = current->getValue();
4934 if (basicClient.get() != nullptr) {
4935 if (basicClient->supportsCameraMute()) {
4936 basicClient->setCameraMute(mOverrideCameraMuteMode);
4937 }
4938 }
4939 }
4940 }
4941
4942 return OK;
4943}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004944
Avichal Rakesh84147132021-11-11 17:47:11 -08004945status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004946 if (args.size() >= 3 && args[1] == String16("start")) {
4947 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004948 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004949 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004950 } else if (args.size() == 2 && args[1] == String16("dump")) {
4951 return printWatchedTags(outFd);
4952 } else if (args.size() >= 2 && args[1] == String16("live")) {
4953 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004954 } else if (args.size() == 2 && args[1] == String16("clear")) {
4955 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004956 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004957 dprintf(outFd, "Camera service watch commands:\n"
4958 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4959 " starts watching the provided tags for clients with provided package\n"
4960 " recognizes tag shorthands like '3a'\n"
4961 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004962 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004963 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08004964 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004965 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08004966 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004967 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004968 return BAD_VALUE;
4969}
4970
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004971status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4972 Mutex::Autolock lock(mLogLock);
4973 size_t tagsIdx; // index of '-m'
4974 String16 tags("");
4975 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4976 if (tagsIdx < args.size() - 1) {
4977 tags = args[tagsIdx + 1];
4978 } else {
4979 dprintf(outFd, "No tags provided.\n");
4980 return BAD_VALUE;
4981 }
4982
4983 size_t clientsIdx; // index of '-c'
4984 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4985 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4986 clientsIdx++);
4987 if (clientsIdx < args.size() - 1) {
4988 clients = args[clientsIdx + 1];
4989 }
4990 parseClientsToWatchLocked(String8(clients));
4991
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004992 // track tags to initialize future clients with the monitoring information
4993 mMonitorTags = String8(tags);
4994
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004995 bool serviceLock = tryLock(mServiceLock);
4996 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004997 auto cameraClients = mActiveClientManager.getAll();
4998 for (const auto &clientDescriptor: cameraClients) {
4999 if (clientDescriptor == nullptr) { continue; }
5000 sp<BasicClient> client = clientDescriptor->getValue();
5001 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005002
5003 if (isClientWatchedLocked(client.get())) {
5004 client->startWatchingTags(mMonitorTags, outFd);
5005 numWatchedClients++;
5006 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005007 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005008 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5009
5010 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005011 return OK;
5012}
5013
5014status_t CameraService::stopWatchingTags(int outFd) {
5015 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005016 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005017 mMonitorTags = String8::empty();
5018
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005019 mWatchedClientPackages.clear();
5020 mWatchedClientsDumpCache.clear();
5021
5022 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005023 auto cameraClients = mActiveClientManager.getAll();
5024 for (const auto &clientDescriptor : cameraClients) {
5025 if (clientDescriptor == nullptr) { continue; }
5026 sp<BasicClient> client = clientDescriptor->getValue();
5027 if (client.get() == nullptr) { continue; }
5028 client->stopWatchingTags(outFd);
5029 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005030 dprintf(outFd, "Stopped watching all clients.\n");
5031 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005032 return OK;
5033}
5034
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005035status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5036 Mutex::Autolock lock(mLogLock);
5037 size_t clearedSize = mWatchedClientsDumpCache.size();
5038 mWatchedClientsDumpCache.clear();
5039 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5040 return OK;
5041}
5042
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005043status_t CameraService::printWatchedTags(int outFd) {
5044 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005045 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005046
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005047 bool printedSomething = false; // tracks if any monitoring information was printed
5048 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005049
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005050 bool serviceLock = tryLock(mServiceLock);
5051 // get all watched clients that are currently connected
5052 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5053 if (clientDescriptor == nullptr) { continue; }
5054
5055 sp<BasicClient> client = clientDescriptor->getValue();
5056 if (client.get() == nullptr) { continue; }
5057 if (!isClientWatchedLocked(client.get())) { continue; }
5058
5059 std::vector<std::string> dumpVector;
5060 client->dumpWatchedEventsToVector(dumpVector);
5061
5062 size_t printIdx = dumpVector.size();
5063 if (printIdx == 0) {
5064 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005065 }
5066
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005067 // Print tag dumps for active client
5068 const String8 &cameraId = clientDescriptor->getKey();
5069 String8 packageName8 = String8(client->getPackageName());
5070 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5071 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5072 while(printIdx > 0) {
5073 printIdx--;
5074 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5075 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005076 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005077 dprintf(outFd, "\n");
5078 packageName8.unlockBuffer();
5079 printedSomething = true;
5080
5081 connectedMonitoredClients.emplace(client->getPackageName());
5082 }
5083 if (serviceLock) { mServiceLock.unlock(); }
5084
5085 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5086 for (const auto &kv: mWatchedClientsDumpCache) {
5087 const String16 &package = kv.first;
5088 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5089 continue;
5090 }
5091
5092 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5093 dprintf(outFd, "%s\n", kv.second.c_str());
5094 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005095 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005096
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005097 if (!printedSomething) {
5098 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005099 }
5100
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005101 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005102}
5103
Avichal Rakesh84147132021-11-11 17:47:11 -08005104// Print all events in vector `events' that came after lastPrintedEvent
5105void printNewWatchedEvents(int outFd,
5106 const char *cameraId,
5107 const String16 &packageName,
5108 const std::vector<std::string> &events,
5109 const std::string &lastPrintedEvent) {
5110 if (events.empty()) { return; }
5111
5112 // index of lastPrintedEvent in events.
5113 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5114 size_t lastPrintedIdx;
5115 for (lastPrintedIdx = 0;
5116 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5117 lastPrintedIdx++);
5118
5119 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5120
5121 String8 packageName8(packageName);
5122 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5123
5124 // print events in chronological order (latest event last)
5125 size_t idxToPrint = lastPrintedIdx;
5126 do {
5127 idxToPrint--;
5128 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5129 } while (idxToPrint != 0);
5130
5131 packageName8.unlockBuffer();
5132}
5133
5134// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5135// command should be interrupted if the user presses the return key, or if user loses any way to
5136// signal interrupt.
5137// If timeoutMs == 0, this function will always return false
5138bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5139 struct timeval startTime;
5140 int startTimeError = gettimeofday(&startTime, nullptr);
5141 if (startTimeError) {
5142 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5143 return true;
5144 }
5145
5146 const nfds_t numFds = 1;
5147 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5148
5149 struct timeval currTime;
5150 char buffer[2];
5151 while(true) {
5152 int currTimeError = gettimeofday(&currTime, nullptr);
5153 if (currTimeError) {
5154 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5155 return true;
5156 }
5157
5158 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5159 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5160 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5161
5162 if (remainingTimeMs <= 0) {
5163 // No user interrupt within timeoutMs, don't interrupt watch command
5164 return false;
5165 }
5166
5167 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5168 if (numFdsUpdated < 0) {
5169 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5170 return true;
5171 }
5172
5173 if (numFdsUpdated == 0) {
5174 // No user input within timeoutMs, don't interrupt watch command
5175 return false;
5176 }
5177
5178 if (!(pollFd.revents & POLLIN)) {
5179 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5180 return true;
5181 }
5182
5183 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5184 if (sizeRead < 0) {
5185 dprintf(outFd, "Error reading user input. Exiting.\n");
5186 return true;
5187 }
5188
5189 if (sizeRead == 0) {
5190 // Reached end of input fd (can happen if input is piped)
5191 // User has no way to signal an interrupt, so interrupt here
5192 return true;
5193 }
5194
5195 if (buffer[0] == '\n') {
5196 // User pressed return, interrupt watch command.
5197 return true;
5198 }
5199 }
5200}
5201
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005202status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5203 int inFd, int outFd) {
5204 // Figure out refresh interval, if present in args
5205 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005206 if (args.size() > 2) {
5207 size_t intervalIdx; // index of '-n'
5208 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5209 intervalIdx++);
5210
5211 size_t intervalValIdx = intervalIdx + 1;
5212 if (intervalValIdx < args.size()) {
5213 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5214 if (errno) { return BAD_VALUE; }
5215 }
5216 }
5217
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005218 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5219 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005220
Avichal Rakesh84147132021-11-11 17:47:11 -08005221 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005222 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005223
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005224 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005225 bool serviceLock = tryLock(mServiceLock);
5226 auto cameraClients = mActiveClientManager.getAll();
5227 if (serviceLock) { mServiceLock.unlock(); }
5228
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005229 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005230 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005231 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005232
5233 sp<BasicClient> client = clientDescriptor->getValue();
5234 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005235 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005236
Avichal Rakesha14d9832021-11-11 01:41:55 -08005237 const String16 &packageName = client->getPackageName();
5238 // This also initializes the map entries with an empty string
5239 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5240
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005241 std::vector<std::string> latestEvents;
5242 client->dumpWatchedEventsToVector(latestEvents);
5243
5244 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005245 String8 cameraId = clientDescriptor->getKey();
5246 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005247 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005248 printableCameraId,
5249 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005250 latestEvents,
5251 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005252 packageNameToLastEvent[packageName] = latestEvents[0];
5253 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005254 }
5255 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005256 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005257 break;
5258 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005259 }
5260 return OK;
5261}
5262
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005263void CameraService::parseClientsToWatchLocked(String8 clients) {
5264 mWatchedClientPackages.clear();
5265
5266 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5267
5268 char *tokenized = clients.lockBuffer(clients.size());
5269 char *savePtr;
5270 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5271
5272 while (nextClient != nullptr) {
5273 if (strcmp(nextClient, allSentinel) == 0) {
5274 // Don't need to track any other package if 'all' is present
5275 mWatchedClientPackages.clear();
5276 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5277 break;
5278 }
5279
5280 // track package names
5281 mWatchedClientPackages.emplace(nextClient);
5282 nextClient = strtok_r(nullptr, ",", &savePtr);
5283 }
5284 clients.unlockBuffer();
5285}
5286
Svet Ganova453d0d2018-01-11 15:37:58 -08005287status_t CameraService::printHelp(int out) {
5288 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005289 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5290 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5291 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005292 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5293 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5294 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005295 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5296 " Valid values 0=OFF, 1=ON for JPEG\n"
5297 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005298 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005299 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005300 " help print this message\n");
5301}
5302
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005303bool CameraService::isClientWatched(const BasicClient *client) {
5304 Mutex::Autolock lock(mLogLock);
5305 return isClientWatchedLocked(client);
5306}
5307
5308bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5309 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5310 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5311}
5312
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005313int32_t CameraService::updateAudioRestriction() {
5314 Mutex::Autolock lock(mServiceLock);
5315 return updateAudioRestrictionLocked();
5316}
5317
5318int32_t CameraService::updateAudioRestrictionLocked() {
5319 int32_t mode = 0;
5320 // iterate through all active client
5321 for (const auto& i : mActiveClientManager.getAll()) {
5322 const auto clientSp = i->getValue();
5323 mode |= clientSp->getAudioRestriction();
5324 }
5325
5326 bool modeChanged = (mAudioRestriction != mode);
5327 mAudioRestriction = mode;
5328 if (modeChanged) {
5329 mAppOps.setCameraAudioRestriction(mode);
5330 }
5331 return mode;
5332}
5333
Cliff Wu646bd612021-11-23 23:21:29 +08005334status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5335 sp<BasicClient> clientSp) {
5336 std::unique_ptr<AutoConditionLock> lock =
5337 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5338 status_t res = NO_ERROR;
5339 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5340 ALOGW("Device %s is not usable!", externalCamId.string());
5341 mInjectionStatusListener->notifyInjectionError(
5342 externalCamId, UNKNOWN_TRANSACTION);
5343 clientSp->notifyError(
5344 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5345 CaptureResultExtras());
5346
5347 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5348 // other clients from connecting in mServiceLockWrapper if held
5349 mServiceLock.unlock();
5350
5351 // Clear caller identity temporarily so client disconnect PID checks work correctly
5352 int64_t token = CameraThreadState::clearCallingIdentity();
5353 clientSp->disconnect();
5354 CameraThreadState::restoreCallingIdentity(token);
5355
5356 // Reacquire mServiceLock
5357 mServiceLock.lock();
5358 }
5359
5360 return res;
5361}
5362
Cliff Wud3a05312021-04-26 23:07:31 +08005363void CameraService::clearInjectionParameters() {
5364 {
5365 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005366 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005367 mInjectionInternalCamId = "";
5368 }
5369 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005370 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005371}
5372
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373}; // namespace android