blob: e2fcb5a97cd254c5626d7b99cc8f8812cbffe92b [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>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Alex Deymo9c2a2c22016-08-25 11:59:14 -070034#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080035#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070036#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080037#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080038#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/CameraClient.h"
74#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"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070091using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080092using hardware::ICameraServiceListener;
93using hardware::camera::common::V1_0::CameraDeviceStatus;
94using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080095using hardware::camera2::utils::CameraIdAndSessionConfiguration;
96using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080097
Mathias Agopian65ab4712010-07-14 17:59:35 -070098// ----------------------------------------------------------------------------
99// Logging support -- this is for debugging only
100// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700101volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
Steve Blockb8a80522011-12-20 16:23:08 +0000103#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
104#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
106static void setLogLevel(int level) {
107 android_atomic_write(level, &gLogLevel);
108}
109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800110// Convenience methods for constructing binder::Status objects for error returns
111
112#define STATUS_ERROR(errorCode, errorString) \
113 binder::Status::fromServiceSpecificError(errorCode, \
114 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
115
116#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
117 binder::Status::fromServiceSpecificError(errorCode, \
118 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
119 __VA_ARGS__))
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700123static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800124static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700125static const String16 sCameraPermission("android.permission.CAMERA");
126static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
127static const String16
128 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800129static const String16 sCameraOpenCloseListenerPermission(
130 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800131
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700132// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
133static constexpr int32_t kVendorClientScore = 200;
134// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
135static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800136const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700137
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700138Mutex CameraService::sProxyMutex;
139sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
140
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800141CameraService::CameraService() :
142 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800143 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700144 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700145 mSoundRef(0), mInitialized(false),
146 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000147 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149}
150
Iliyan Malchev8951a972011-04-14 16:55:59 -0700151void CameraService::onFirstRef()
152{
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800154
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 BnCameraService::onFirstRef();
156
Ruben Brunk99e69712015-05-26 17:25:07 -0700157 // Update battery life tracking if service is restarting
158 BatteryNotifier& notifier(BatteryNotifier::getInstance());
159 notifier.noteResetCamera();
160 notifier.noteResetFlashlight();
161
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800162 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800163
Emilian Peevf53f66e2017-04-11 14:29:43 +0100164 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800165 if (res == OK) {
166 mInitialized = true;
167 }
168
Svet Ganova453d0d2018-01-11 15:37:58 -0800169 mUidPolicy = new UidPolicy(this);
170 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800171 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
172 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700173 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700174 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
175 if (hcs->registerAsService() != android::OK) {
176 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
177 __FUNCTION__);
178 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700179
180 // This needs to be last call in this function, so that it's as close to
181 // ServiceManager::addService() as possible.
182 CameraService::pingCameraServiceProxy();
183 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800184}
185
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800186status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100188
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800189 std::vector<std::string> deviceIds;
190 {
191 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800192
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800193 if (nullptr == mCameraProviderManager.get()) {
194 mCameraProviderManager = new CameraProviderManager();
195 res = mCameraProviderManager->initialize(this);
196 if (res != OK) {
197 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
198 __FUNCTION__, strerror(-res), res);
199 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100200 }
201 }
202
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800203
204 // Setup vendor tags before we call get_camera_info the first time
205 // because HAL might need to setup static vendor keys in get_camera_info
206 // TODO: maybe put this into CameraProviderManager::initialize()?
207 mCameraProviderManager->setUpVendorTags();
208
209 if (nullptr == mFlashlight.get()) {
210 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700211 }
212
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800213 res = mFlashlight->findFlashUnits();
214 if (res != OK) {
215 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
216 }
217
218 deviceIds = mCameraProviderManager->getCameraDeviceIds();
219 }
220
221
222 for (auto& cameraId : deviceIds) {
223 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800224 if (getCameraState(id8) == nullptr) {
225 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
226 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800227 }
228
229 return OK;
230}
231
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700232sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800233#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700234 Mutex::Autolock al(sProxyMutex);
235 if (sCameraServiceProxy == nullptr) {
236 sp<IServiceManager> sm = defaultServiceManager();
237 // Use checkService because cameraserver normally starts before the
238 // system server and the proxy service. So the long timeout that getService
239 // has before giving up is inappropriate.
240 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
241 if (binder != nullptr) {
242 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
243 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700244 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800245#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700246 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700247}
248
249void CameraService::pingCameraServiceProxy() {
250 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
251 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700252 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700253}
254
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700255void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
256 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800257 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800258 for (auto& i : mListenerList) {
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700259 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
260 i->getListenerUid())) {
261 ALOGV("Skipping torch callback for system-only camera device %s",
262 cameraId.c_str());
263 continue;
264 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700265 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800266 }
267}
268
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800270 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800271 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800272 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273}
274
Emilian Peevaee727d2017-05-04 16:35:48 +0100275void CameraService::onNewProviderRegistered() {
276 enumerateProviders();
277}
278
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700279void CameraService::filterAPI1SystemCameraLocked(
280 const std::vector<std::string> &normalDeviceIds) {
281 mNormalDeviceIdsWithoutSystemCamera.clear();
282 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700283 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
284 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
285 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
286 continue;
287 }
288 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700289 // All system camera ids will necessarily come after public camera
290 // device ids as per the HAL interface contract.
291 break;
292 }
293 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
294 }
295 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
296 mNormalDeviceIdsWithoutSystemCamera.size());
297}
298
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700299status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
300 auto state = getCameraState(cameraId);
301 if (state != nullptr) {
302 *kind = state->getSystemCameraKind();
303 return OK;
304 }
305 // Hidden physical camera ids won't have CameraState
306 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
307}
308
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800309void CameraService::updateCameraNumAndIds() {
310 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700311 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
312 // Excludes hidden secure cameras
313 mNumberOfCameras =
314 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
315 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800316 mNormalDeviceIds =
317 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700318 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800319}
320
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100321void CameraService::addStates(const String8 id) {
322 std::string cameraId(id.c_str());
323 hardware::camera::common::V1_0::CameraResourceCost cost;
324 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700325 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100326 if (res != OK) {
327 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
328 return;
329 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700330 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
331 if (res != OK) {
332 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
333 return;
334 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100335 std::set<String8> conflicting;
336 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
337 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
338 }
339
340 {
341 Mutex::Autolock lock(mCameraStatesLock);
342 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700343 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100344 }
345
346 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100347 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100348 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800349
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700350 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100351 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800352
353 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100354 logDeviceAdded(id, "Device added");
355}
356
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100357void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800358 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100359 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100360 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100361 mTorchStatusMap.removeItem(id);
362 }
363
364 {
365 Mutex::Autolock lock(mCameraStatesLock);
366 mCameraStates.erase(id);
367 }
368}
369
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800370void CameraService::onDeviceStatusChanged(const String8& id,
371 CameraDeviceStatus newHalStatus) {
372 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
373 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700374
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800375 StatusInternal newStatus = mapToInternal(newHalStatus);
376
Ruben Brunkcc776712015-02-17 20:18:47 -0800377 std::shared_ptr<CameraState> state = getCameraState(id);
378
379 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700380 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100381 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700382 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100383
384 // First add as absent to make sure clients are notified below
385 addStates(id);
386
387 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700388 } else {
389 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
390 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700391 return;
392 }
393
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800394 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800395
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800396 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800397 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700398 return;
399 }
400
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800401 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700402 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
403 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800404
405 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
406 // to this device until the status changes
407 updateStatus(StatusInternal::NOT_PRESENT, id);
408
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800409 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700410 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800411 // Don't do this in updateStatus to avoid deadlock over mServiceLock
412 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700413
Ruben Brunkcc776712015-02-17 20:18:47 -0800414 // Remove cached shim parameters
415 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700416
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800417 // Remove online as well as offline client from the list of active clients,
418 // if they are present
419 clientToDisconnectOnline = removeClientLocked(id);
420 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700421 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800422
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800423 disconnectClient(id, clientToDisconnectOnline);
424 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700425
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100426 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800427 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800428 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700429 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
430 newStatus));
431 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800432 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700433 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800434}
Igor Murashkincba2c162013-03-20 15:56:31 -0700435
Shuzhen Wang43858162020-01-10 13:42:15 -0800436void CameraService::onDeviceStatusChanged(const String8& id,
437 const String8& physicalId,
438 CameraDeviceStatus newHalStatus) {
439 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
440 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
441
442 StatusInternal newStatus = mapToInternal(newHalStatus);
443
444 std::shared_ptr<CameraState> state = getCameraState(id);
445
446 if (state == nullptr) {
447 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
448 __FUNCTION__, id.string(), physicalId.string());
449 return;
450 }
451
452 StatusInternal logicalCameraStatus = state->getStatus();
453 if (logicalCameraStatus != StatusInternal::PRESENT &&
454 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
455 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
456 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
457 return;
458 }
459
460 bool updated = false;
461 if (newStatus == StatusInternal::PRESENT) {
462 updated = state->removeUnavailablePhysicalId(physicalId);
463 } else {
464 updated = state->addUnavailablePhysicalId(physicalId);
465 }
466
467 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800468 String8 idCombo = id + " : " + physicalId;
469 if (newStatus == StatusInternal::PRESENT) {
470 logDeviceAdded(idCombo,
471 String8::format("Device status changed to %d", newStatus));
472 } else {
473 logDeviceRemoved(idCombo,
474 String8::format("Device status changed to %d", newStatus));
475 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700476 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
477 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
478 if (getSystemCameraKind(id, &deviceKind) != OK) {
479 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
480 return;
481 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800482 String16 id16(id), physicalId16(physicalId);
483 Mutex::Autolock lock(mStatusListenerLock);
484 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700485 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
486 listener->getListenerPid(), listener->getListenerUid())) {
487 ALOGV("Skipping discovery callback for system-only camera device %s",
488 id.c_str());
489 continue;
490 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800491 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
492 id16, physicalId16);
493 }
494 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700495}
496
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800497void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
498 if (clientToDisconnect.get() != nullptr) {
499 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
500 __FUNCTION__, id.string());
501 // Notify the client of disconnection
502 clientToDisconnect->notifyError(
503 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
504 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800505 clientToDisconnect->disconnect();
506 }
507}
508
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800509void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800510 TorchModeStatus newStatus) {
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700511 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
512 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
513 if (res != OK) {
514 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
515 cameraId.string());
516 return;
517 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800518 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700519 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800520}
521
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800522void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700523 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800524 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
525 __FUNCTION__, cameraId.string(), newStatus);
526
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800527 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800528 status_t res = getTorchStatusLocked(cameraId, &status);
529 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700530 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
531 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800532 return;
533 }
534 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800535 return;
536 }
537
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800538 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800539 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800540 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
541 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800542 return;
543 }
544
Ruben Brunkcc776712015-02-17 20:18:47 -0800545 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700546 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700547 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700548 auto iter = mTorchUidMap.find(cameraId);
549 if (iter != mTorchUidMap.end()) {
550 int oldUid = iter->second.second;
551 int newUid = iter->second.first;
552 BatteryNotifier& notifier(BatteryNotifier::getInstance());
553 if (oldUid != newUid) {
554 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800555 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700556 notifier.noteFlashlightOff(cameraId, oldUid);
557 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700559 notifier.noteFlashlightOn(cameraId, newUid);
560 }
561 iter->second.second = newUid;
562 } else {
563 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800564 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700565 notifier.noteFlashlightOn(cameraId, oldUid);
566 } else {
567 notifier.noteFlashlightOff(cameraId, oldUid);
568 }
569 }
570 }
571 }
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -0700572 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800573}
574
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700575static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
576 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
577 checkPermission(sCameraPermission, callingPid, callingUid);
578}
579
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700581 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100582 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700583 bool hasSystemCameraPermissions =
584 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
585 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700586 switch (type) {
587 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700588 if (hasSystemCameraPermissions) {
589 *numCameras = static_cast<int>(mNormalDeviceIds.size());
590 } else {
591 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
592 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800593 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700594 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700595 if (hasSystemCameraPermissions) {
596 *numCameras = mNumberOfCameras;
597 } else {
598 *numCameras = mNumberOfCamerasWithoutSystemCamera;
599 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800600 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700601 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800602 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700603 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800604 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
605 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700606 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800607 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608}
609
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800610Status CameraService::getCameraInfo(int cameraId,
611 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700612 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100613 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700614 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
615 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
616 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
617 "characteristics for system only device %s: ", cameraIdStr.c_str());
618 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100619
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800620 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800621 return STATUS_ERROR(ERROR_DISCONNECTED,
622 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700623 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700624 bool hasSystemCameraPermissions =
625 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
626 CameraThreadState::getCallingUid());
627 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
628 if (hasSystemCameraPermissions) {
629 cameraIdBound = mNumberOfCameras;
630 }
631 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800632 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
633 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634 }
635
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800636 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800637 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700638 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100639 if (err != OK) {
640 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
641 "Error retrieving camera info from device %d: %s (%d)", cameraId,
642 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800643 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100644
Ruben Brunkcc776712015-02-17 20:18:47 -0800645 return ret;
646}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700647
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800648std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
650 auto callingPid = CameraThreadState::getCallingPid();
651 auto callingUid = CameraThreadState::getCallingUid();
652 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
653 getpid() == callingPid) {
654 deviceIds = &mNormalDeviceIds;
655 }
656 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800657 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700658 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800659 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800660 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800661
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700662 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800663}
664
665String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
666 Mutex::Autolock lock(mServiceLock);
667 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800668}
669
670Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800671 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700672 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700673 if (!cameraInfo) {
674 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800675 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700676 }
677
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800678 if (!mInitialized) {
679 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800680 return STATUS_ERROR(ERROR_DISCONNECTED,
681 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700682 }
683
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700684 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
685 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
686 "characteristics for system only device %s: ", String8(cameraId).string());
687 }
688
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800689 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800690
Emilian Peevf53f66e2017-04-11 14:29:43 +0100691 status_t res = mCameraProviderManager->getCameraCharacteristics(
692 String8(cameraId).string(), cameraInfo);
693 if (res != OK) {
694 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
695 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
696 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700697 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700698 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
699 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
700 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
701 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
702 "for device %s", String8(cameraId).string());
703 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700704 int callingPid = CameraThreadState::getCallingPid();
705 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100706 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700707 // If it's not calling from cameraserver, check the permission only if
708 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
709 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100710 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700711 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700712 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100713 res = cameraInfo->removePermissionEntries(
714 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
715 &tagsRemoved);
716 if (res != OK) {
717 cameraInfo->clear();
718 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
719 " characteristics needing camera permission for device %s: %s (%d)",
720 String8(cameraId).string(), strerror(-res), res);
721 }
722 }
723
724 if (!tagsRemoved.empty()) {
725 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
726 tagsRemoved.data(), tagsRemoved.size());
727 if (res != OK) {
728 cameraInfo->clear();
729 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
730 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
731 strerror(-res), res);
732 }
733 }
734
Zhijun He2b59be82013-09-25 10:14:30 -0700735 return ret;
736}
737
Ruben Brunkcc776712015-02-17 20:18:47 -0800738String8 CameraService::getFormattedCurrentTime() {
739 time_t now = time(nullptr);
740 char formattedTime[64];
741 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
742 return String8(formattedTime);
743}
744
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745Status CameraService::getCameraVendorTagDescriptor(
746 /*out*/
747 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700748 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800749 if (!mInitialized) {
750 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800751 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800752 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800753 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
754 if (globalDescriptor != nullptr) {
755 *desc = *(globalDescriptor.get());
756 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800757 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800758}
759
Emilian Peev71c73a22017-03-21 16:35:51 +0000760Status CameraService::getCameraVendorTagCache(
761 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
762 ATRACE_CALL();
763 if (!mInitialized) {
764 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
765 return STATUS_ERROR(ERROR_DISCONNECTED,
766 "Camera subsystem not available");
767 }
768 sp<VendorTagDescriptorCache> globalCache =
769 VendorTagDescriptorCache::getGlobalVendorTagCache();
770 if (globalCache != nullptr) {
771 *cache = *(globalCache.get());
772 }
773 return Status::ok();
774}
775
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800776int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700777 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800778
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800779 int deviceVersion = 0;
780
Emilian Peevf53f66e2017-04-11 14:29:43 +0100781 status_t res;
782 hardware::hidl_version maxVersion{0,0};
783 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
784 &maxVersion);
785 if (res != OK) return -1;
786 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800787
Emilian Peevf53f66e2017-04-11 14:29:43 +0100788 hardware::CameraInfo info;
789 if (facing) {
790 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800791 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100792 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800793 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100794
Igor Murashkin634a5152013-02-20 17:15:11 -0800795 return deviceVersion;
796}
797
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800798Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700799 switch(err) {
800 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800801 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800802 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800803 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
804 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800805 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 return STATUS_ERROR(ERROR_DISCONNECTED,
807 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700808 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800809 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
810 "Camera HAL encountered error %d: %s",
811 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700812 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800813}
814
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800816 const sp<IInterface>& cameraCb, const String16& packageName,
817 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
818 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
819 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 /*out*/sp<BasicClient>* client) {
821
Ruben Brunkcc776712015-02-17 20:18:47 -0800822 if (halVersion < 0 || halVersion == deviceVersion) {
823 // Default path: HAL version is unspecified by caller, create CameraClient
824 // based on device version reported by the HAL.
825 switch(deviceVersion) {
826 case CAMERA_DEVICE_API_VERSION_1_0:
827 if (effectiveApiLevel == API_1) { // Camera1 API route
828 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800829 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800830 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700831 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 } else { // Camera2 API route
833 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800834 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800835 "Camera device \"%s\" HAL version %d does not support camera2 API",
836 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 }
838 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800839 case CAMERA_DEVICE_API_VERSION_3_0:
840 case CAMERA_DEVICE_API_VERSION_3_1:
841 case CAMERA_DEVICE_API_VERSION_3_2:
842 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700843 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700844 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800845 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800846 if (effectiveApiLevel == API_1) { // Camera1 API route
847 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800848 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800849 cameraId, api1CameraId,
850 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700851 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800852 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800853 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
854 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800855 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
856 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800857 }
858 break;
859 default:
860 // Should not be reachable
861 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800862 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800863 "Camera device \"%s\" has unknown HAL version %d",
864 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800865 }
866 } else {
867 // A particular HAL version is requested by caller. Create CameraClient
868 // based on the requested HAL version.
869 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
870 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
871 // Only support higher HAL version device opened as HAL1.0 device.
872 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800873 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800874 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700875 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800876 } else {
877 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
878 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
879 " opened as HAL %x device", halVersion, deviceVersion,
880 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800881 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800882 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
883 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800884 }
885 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800886 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800887}
888
Ruben Brunk6267b532015-04-30 17:44:07 -0700889String8 CameraService::toString(std::set<userid_t> intSet) {
890 String8 s("");
891 bool first = true;
892 for (userid_t i : intSet) {
893 if (first) {
894 s.appendFormat("%d", i);
895 first = false;
896 } else {
897 s.appendFormat(", %d", i);
898 }
899 }
900 return s;
901}
902
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800903int32_t CameraService::mapToInterface(TorchModeStatus status) {
904 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
905 switch (status) {
906 case TorchModeStatus::NOT_AVAILABLE:
907 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
908 break;
909 case TorchModeStatus::AVAILABLE_OFF:
910 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
911 break;
912 case TorchModeStatus::AVAILABLE_ON:
913 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
914 break;
915 default:
916 ALOGW("Unknown new flash status: %d", status);
917 }
918 return serviceStatus;
919}
920
921CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
922 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
923 switch (status) {
924 case CameraDeviceStatus::NOT_PRESENT:
925 serviceStatus = StatusInternal::NOT_PRESENT;
926 break;
927 case CameraDeviceStatus::PRESENT:
928 serviceStatus = StatusInternal::PRESENT;
929 break;
930 case CameraDeviceStatus::ENUMERATING:
931 serviceStatus = StatusInternal::ENUMERATING;
932 break;
933 default:
934 ALOGW("Unknown new HAL device status: %d", status);
935 }
936 return serviceStatus;
937}
938
939int32_t CameraService::mapToInterface(StatusInternal status) {
940 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
941 switch (status) {
942 case StatusInternal::NOT_PRESENT:
943 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
944 break;
945 case StatusInternal::PRESENT:
946 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
947 break;
948 case StatusInternal::ENUMERATING:
949 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
950 break;
951 case StatusInternal::NOT_AVAILABLE:
952 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
953 break;
954 case StatusInternal::UNKNOWN:
955 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
956 break;
957 default:
958 ALOGW("Unknown new internal device status: %d", status);
959 }
960 return serviceStatus;
961}
962
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800963Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700964 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700965
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800966 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800967 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800968 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800969 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800970 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800971 sp<ICameraClient>{nullptr}, id, cameraId,
972 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800973 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700974 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800975 ).isOk()) {
976 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700977 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800978 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700979}
980
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800981Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700982 /*out*/
983 CameraParameters* parameters) {
984
985 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
986
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800987 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700988
989 if (parameters == NULL) {
990 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700992 }
993
Ruben Brunkcc776712015-02-17 20:18:47 -0800994 String8 id = String8::format("%d", cameraId);
995
996 // Check if we already have parameters
997 {
998 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700999 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001000 auto cameraState = getCameraState(id);
1001 if (cameraState == nullptr) {
1002 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001003 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1004 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 }
1006 CameraParameters p = cameraState->getShimParams();
1007 if (!p.isEmpty()) {
1008 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001009 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001010 }
1011 }
1012
Jayant Chowdhary12361932018-08-27 14:46:13 -07001013 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001014 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001015 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001016 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 // Error already logged by callee
1018 return ret;
1019 }
1020
1021 // Check for parameters again
1022 {
1023 // Scope for service lock
1024 Mutex::Autolock lock(mServiceLock);
1025 auto cameraState = getCameraState(id);
1026 if (cameraState == nullptr) {
1027 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001028 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1029 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001030 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001031 CameraParameters p = cameraState->getShimParams();
1032 if (!p.isEmpty()) {
1033 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001034 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001035 }
1036 }
1037
Ruben Brunkcc776712015-02-17 20:18:47 -08001038 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1039 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001040 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001041}
1042
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001043// Can camera service trust the caller based on the calling UID?
1044static bool isTrustedCallingUid(uid_t uid) {
1045 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001046 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001047 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001048 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001049 return true;
1050 default:
1051 return false;
1052 }
1053}
1054
Nicholas Sauera3620332019-04-03 14:05:17 -07001055static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1056 PermissionController pc;
1057 uid = pc.getPackageUid(packageName, 0);
1058 if (uid <= 0) {
1059 ALOGE("Unknown package: '%s'", String8(packageName).string());
1060 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1061 return BAD_VALUE;
1062 }
1063
1064 if (userId < 0) {
1065 ALOGE("Invalid user: %d", userId);
1066 dprintf(err, "Invalid user: %d\n", userId);
1067 return BAD_VALUE;
1068 }
1069
1070 uid = multiuser_get_uid(userId, uid);
1071 return NO_ERROR;
1072}
1073
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001074Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001075 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1076 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001077
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001078#ifdef __BRILLO__
1079 UNUSED(clientName8);
1080 UNUSED(clientUid);
1081 UNUSED(clientPid);
1082 UNUSED(originalClientPid);
1083#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001084 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1085 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001086 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001087 return allowed;
1088 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001089#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001090
Jayant Chowdhary12361932018-08-27 14:46:13 -07001091 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001092
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001093 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001094 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1095 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001096 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1097 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001098 }
1099
Ruben Brunkcc776712015-02-17 20:18:47 -08001100 if (getCameraState(cameraId) == nullptr) {
1101 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1102 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001103 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1104 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 }
1106
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001107 status_t err = checkIfDeviceIsUsable(cameraId);
1108 if (err != NO_ERROR) {
1109 switch(err) {
1110 case -ENODEV:
1111 case -EBUSY:
1112 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1113 "No camera device with ID \"%s\" currently available", cameraId.string());
1114 default:
1115 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1116 "Unknown error connecting to ID \"%s\"", cameraId.string());
1117 }
1118 }
1119 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001120}
1121
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001122Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001123 const String8& clientName8, int& clientUid, int& clientPid,
1124 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001125 int callingPid = CameraThreadState::getCallingPid();
1126 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001128 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001130 clientUid = callingUid;
1131 } else if (!isTrustedCallingUid(callingUid)) {
1132 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1133 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001134 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1135 "Untrusted caller (calling PID %d, UID %d) trying to "
1136 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1137 callingPid, callingUid, cameraId.string(),
1138 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 }
1140
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001141 // Check if we can trust clientPid
1142 if (clientPid == USE_CALLING_PID) {
1143 clientPid = callingPid;
1144 } else if (!isTrustedCallingUid(callingUid)) {
1145 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1146 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001147 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1148 "Untrusted caller (calling PID %d, UID %d) trying to "
1149 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1150 callingPid, callingUid, cameraId.string(),
1151 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001152 }
1153
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001154 if (shouldRejectSystemCameraConnection(cameraId)) {
1155 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1156 cameraId.c_str());
1157 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1158 "available", cameraId.string());
1159 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001160 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1161 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1162 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1163 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1164 "found while trying to query device kind", cameraId.string());
1165
1166 }
1167
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001168 // If it's not calling from cameraserver, check the permission if the
1169 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1170 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001171 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001172 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001173 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001174 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1176 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1177 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001178 }
1179
Svet Ganova453d0d2018-01-11 15:37:58 -08001180 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001181 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001182 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001183 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1184 clientPid, clientUid);
1185 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001186 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1187 "calling UID %d proc state %" PRId32 ")",
1188 clientName8.string(), clientUid, clientPid, cameraId.string(),
1189 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001190 }
1191
Michael Grooverd1d435a2018-12-18 17:39:42 -08001192 // If sensor privacy is enabled then prevent access to the camera
1193 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1194 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1195 return STATUS_ERROR_FMT(ERROR_DISABLED,
1196 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1197 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1198 }
1199
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001200 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1201 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001202 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001203 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204
Ruben Brunk6267b532015-04-30 17:44:07 -07001205 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001206
Ruben Brunka8ca9152015-04-07 14:23:40 -07001207 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001208 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001209 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001210 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001211 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1212 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1213 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001214 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1215 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1216 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001217 }
1218
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001219 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001220}
1221
1222status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1223 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001224 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 if (cameraState == nullptr) {
1226 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1227 cameraId.string());
1228 return -ENODEV;
1229 }
1230
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001231 StatusInternal currentStatus = cameraState->getStatus();
1232 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1234 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001235 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001236 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1238 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001239 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001240 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001241
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001243}
1244
Ruben Brunkcc776712015-02-17 20:18:47 -08001245void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1246 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001247
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 // Make a descriptor for the incoming client
1249 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1250 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1251
1252 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1253 String8(client->getPackageName()));
1254
1255 if (evicted.size() > 0) {
1256 // This should never happen - clients should already have been removed in disconnect
1257 for (auto& i : evicted) {
1258 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1259 __FUNCTION__, i->getKey().string());
1260 }
1261
1262 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1263 __FUNCTION__);
1264 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001265
1266 // And register a death notification for the client callback. Do
1267 // this last to avoid Binder policy where a nested Binder
1268 // transaction might be pre-empted to service the client death
1269 // notification if the client process dies before linkToDeath is
1270 // invoked.
1271 sp<IBinder> remoteCallback = client->getRemote();
1272 if (remoteCallback != nullptr) {
1273 remoteCallback->linkToDeath(this);
1274 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001275}
1276
1277status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1278 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1279 /*out*/
1280 sp<BasicClient>* client,
1281 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001282 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001283 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001284 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001285 DescriptorPtr clientDescriptor;
1286 {
1287 if (effectiveApiLevel == API_1) {
1288 // If we are using API1, any existing client for this camera ID with the same remote
1289 // should be returned rather than evicted to allow MediaRecorder to work properly.
1290
1291 auto current = mActiveClientManager.get(cameraId);
1292 if (current != nullptr) {
1293 auto clientSp = current->getValue();
1294 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001295 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1296 ALOGW("CameraService connect called from same client, but with a different"
1297 " API level, evicting prior client...");
1298 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001300 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 *client = clientSp;
1302 return NO_ERROR;
1303 }
1304 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001305 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001306 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001307
Ruben Brunkcc776712015-02-17 20:18:47 -08001308 // Get current active client PIDs
1309 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1310 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001311
Emilian Peev8131a262017-02-01 12:33:43 +00001312 std::vector<int> priorityScores(ownerPids.size());
1313 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001314
Emilian Peev8131a262017-02-01 12:33:43 +00001315 // Get priority scores of all active PIDs
1316 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1317 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1318 /*out*/&priorityScores[0]);
1319 if (err != OK) {
1320 ALOGE("%s: Priority score query failed: %d",
1321 __FUNCTION__, err);
1322 return err;
1323 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001324
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001326 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001327 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001328 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001329 resource_policy::ClientPriority(priorityScores[i], states[i],
1330 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001331 }
1332 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001333
Ruben Brunkcc776712015-02-17 20:18:47 -08001334 // Get state for the given cameraId
1335 auto state = getCameraState(cameraId);
1336 if (state == nullptr) {
1337 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1338 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001339 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001340 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001341 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001342
1343 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001344 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001345 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1346 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001347 priorityScores[priorityScores.size() - 1],
1348 clientPid,
1349 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001350
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001351 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1352
Ruben Brunkcc776712015-02-17 20:18:47 -08001353 // Find clients that would be evicted
1354 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1355
1356 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1357 // background, so we cannot do evictions
1358 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1359 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1360 " priority).", clientPid);
1361
1362 sp<BasicClient> clientSp = clientDescriptor->getValue();
1363 String8 curTime = getFormattedCurrentTime();
1364 auto incompatibleClients =
1365 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1366
1367 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001368 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001370 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001371
1372 for (auto& i : incompatibleClients) {
1373 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001374 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1375 i->getKey().string(),
1376 String8{i->getValue()->getPackageName()}.string(),
1377 i->getOwnerId(), i->getPriority().getScore(),
1378 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001379 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001380 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001381 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001382 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001383 }
1384
1385 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001386 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001387 mEventLog.add(msg);
1388
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001389 auto current = mActiveClientManager.get(cameraId);
1390 if (current != nullptr) {
1391 return -EBUSY; // CAMERA_IN_USE
1392 } else {
1393 return -EUSERS; // MAX_CAMERAS_IN_USE
1394 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001395 }
1396
1397 for (auto& i : evicted) {
1398 sp<BasicClient> clientSp = i->getValue();
1399 if (clientSp.get() == nullptr) {
1400 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1401
1402 // TODO: Remove this
1403 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1404 __FUNCTION__);
1405 mActiveClientManager.remove(i);
1406 continue;
1407 }
1408
1409 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1410 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001411 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001412
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001414 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001415 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1416 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001417 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001418 i->getOwnerId(), i->getPriority().getScore(),
1419 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001420 packageName.string(), clientPid, clientPriority.getScore(),
1421 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001422
1423 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001424 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001426 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001427 }
1428
Ruben Brunkcc776712015-02-17 20:18:47 -08001429 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1430 // other clients from connecting in mServiceLockWrapper if held
1431 mServiceLock.unlock();
1432
1433 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001434 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001435
1436 // Destroy evicted clients
1437 for (auto& i : evictedClients) {
1438 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001439 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001441
Jayant Chowdhary12361932018-08-27 14:46:13 -07001442 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001443
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001444 for (const auto& i : evictedClients) {
1445 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1446 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1447 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1448 if (ret == TIMED_OUT) {
1449 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1450 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1451 mActiveClientManager.toString().string());
1452 return -EBUSY;
1453 }
1454 if (ret != NO_ERROR) {
1455 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1456 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1457 ret, mActiveClientManager.toString().string());
1458 return ret;
1459 }
1460 }
1461
1462 evictedClients.clear();
1463
Ruben Brunkcc776712015-02-17 20:18:47 -08001464 // Once clients have been disconnected, relock
1465 mServiceLock.lock();
1466
1467 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1468 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1469 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001470 }
1471
Ruben Brunkcc776712015-02-17 20:18:47 -08001472 *partial = clientDescriptor;
1473 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001474}
1475
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001477 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001478 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001479 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001480 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001481 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001482 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001484
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001485 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001487
1488 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001489 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001490 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001491 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1492 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001494 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001495 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001497 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 }
1499
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001500 *device = client;
1501 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502}
1503
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001504Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001505 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001506 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001507 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001508 int clientUid,
1509 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001510 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001511
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001512 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001513 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001514
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001515 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001516 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001517 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001518 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1519 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001520
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001521 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001522 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001523 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001525 }
1526
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001527 *device = client;
1528 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001529}
1530
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001531bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1532 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001533 // If the client is not a vendor client, don't add listener if
1534 // a) the camera is a publicly hidden secure camera OR
1535 // b) the camera is a system only camera and the client doesn't
1536 // have android.permission.SYSTEM_CAMERA permissions.
1537 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1538 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1539 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001540 return true;
1541 }
1542 return false;
1543}
1544
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001545bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1546 // Rules for rejection:
1547 // 1) If cameraserver tries to access this camera device, accept the
1548 // connection.
1549 // 2) The camera device is a publicly hidden secure camera device AND some
1550 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1551 // reject it.
1552 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1553 // and the serving thread is a non hwbinder thread, the client must have
1554 // android.permission.SYSTEM_CAMERA permissions to connect.
1555
1556 int cPid = CameraThreadState::getCallingPid();
1557 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001558 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1559 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1560 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1561 return true;
1562 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001563
1564 // (1) Cameraserver trying to connect, accept.
1565 if (CameraThreadState::getCallingPid() == getpid()) {
1566 return false;
1567 }
1568 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001569 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001570 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1571 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1572 return true;
1573 }
1574 // (3) Here we only check for permissions if it is a system only camera device. This is since
1575 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1576 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1577 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001578 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001579 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1580 !hasPermissionsForSystemCamera(cPid, cUid)) {
1581 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1582 cameraId.c_str());
1583 return true;
1584 }
1585
1586 return false;
1587}
1588
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001589Status CameraService::connectDevice(
1590 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001591 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001592 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001593 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001594 int clientUid,
1595 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001596 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001597
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001598 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001600 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001601 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001602 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001603
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001604 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001605 std::string vendorClient =
1606 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1607 clientPackageNameAdj = String16(vendorClient.c_str());
1608 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001610 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001611 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001612 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001613
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001614 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001615 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001616 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001617 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001618 }
1619
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620 *device = client;
1621 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001622}
1623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624template<class CALLBACK, class CLIENT>
1625Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001626 int api1CameraId, int halVersion, const String16& clientPackageName,
1627 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1628 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001629 /*out*/sp<CLIENT>& device) {
1630 binder::Status ret = binder::Status::ok();
1631
1632 String8 clientName8(clientPackageName);
1633
1634 int originalClientPid = 0;
1635
1636 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1637 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1638 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1639 static_cast<int>(effectiveApiLevel));
1640
1641 sp<CLIENT> client = nullptr;
1642 {
1643 // Acquire mServiceLock and prevent other clients from connecting
1644 std::unique_ptr<AutoConditionLock> lock =
1645 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1646
1647 if (lock == nullptr) {
1648 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1649 , clientPid);
1650 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1651 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1652 cameraId.string(), clientName8.string(), clientPid);
1653 }
1654
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001655 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001656 if(!(ret = validateConnectLocked(cameraId, clientName8,
1657 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1658 return ret;
1659 }
1660
1661 // Check the shim parameters after acquiring lock, if they have already been updated and
1662 // we were doing a shim update, return immediately
1663 if (shimUpdateOnly) {
1664 auto cameraState = getCameraState(cameraId);
1665 if (cameraState != nullptr) {
1666 if (!cameraState->getShimParams().isEmpty()) return ret;
1667 }
1668 }
1669
1670 status_t err;
1671
1672 sp<BasicClient> clientTmp = nullptr;
1673 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1674 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1675 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1676 /*out*/&partial)) != NO_ERROR) {
1677 switch (err) {
1678 case -ENODEV:
1679 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1680 "No camera device with ID \"%s\" currently available",
1681 cameraId.string());
1682 case -EBUSY:
1683 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1684 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1685 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001686 case -EUSERS:
1687 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1688 "Too many cameras already open, cannot open camera \"%s\"",
1689 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001690 default:
1691 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1692 "Unexpected error %s (%d) opening camera \"%s\"",
1693 strerror(-err), err, cameraId.string());
1694 }
1695 }
1696
1697 if (clientTmp.get() != nullptr) {
1698 // Handle special case for API1 MediaRecorder where the existing client is returned
1699 device = static_cast<CLIENT*>(clientTmp.get());
1700 return ret;
1701 }
1702
1703 // give flashlight a chance to close devices if necessary.
1704 mFlashlight->prepareDeviceOpen(cameraId);
1705
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001706 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001707 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001708 if (facing == -1) {
1709 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1710 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1711 "Unable to get camera device \"%s\" facing", cameraId.string());
1712 }
1713
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001714 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001715 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001716 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001717 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001718 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001719 /*out*/&tmp)).isOk()) {
1720 return ret;
1721 }
1722 client = static_cast<CLIENT*>(tmp.get());
1723
1724 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1725 __FUNCTION__);
1726
Emilian Peevbd8c5032018-02-14 23:05:40 +00001727 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001728 if (err != OK) {
1729 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001730 // Errors could be from the HAL module open call or from AppOpsManager
1731 switch(err) {
1732 case BAD_VALUE:
1733 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1734 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1735 case -EBUSY:
1736 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1737 "Camera \"%s\" is already open", cameraId.string());
1738 case -EUSERS:
1739 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1740 "Too many cameras already open, cannot open camera \"%s\"",
1741 cameraId.string());
1742 case PERMISSION_DENIED:
1743 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1744 "No permission to open camera \"%s\"", cameraId.string());
1745 case -EACCES:
1746 return STATUS_ERROR_FMT(ERROR_DISABLED,
1747 "Camera \"%s\" disabled by policy", cameraId.string());
1748 case -ENODEV:
1749 default:
1750 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1751 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1752 strerror(-err), err);
1753 }
1754 }
1755
1756 // Update shim paremeters for legacy clients
1757 if (effectiveApiLevel == API_1) {
1758 // Assume we have always received a Client subclass for API1
1759 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1760 String8 rawParams = shimClient->getParameters();
1761 CameraParameters params(rawParams);
1762
1763 auto cameraState = getCameraState(cameraId);
1764 if (cameraState != nullptr) {
1765 cameraState->setShimParams(params);
1766 } else {
1767 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1768 __FUNCTION__, cameraId.string());
1769 }
1770 }
1771
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001772 // Set rotate-and-crop override behavior
1773 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1774 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1775 }
1776
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001777 if (shimUpdateOnly) {
1778 // If only updating legacy shim parameters, immediately disconnect client
1779 mServiceLock.unlock();
1780 client->disconnect();
1781 mServiceLock.lock();
1782 } else {
1783 // Otherwise, add client to active clients list
1784 finishConnectLocked(client, partial);
1785 }
1786 } // lock is destroyed, allow further connect calls
1787
1788 // Important: release the mutex here so the client can call back into the service from its
1789 // destructor (can be at the end of the call)
1790 device = client;
1791 return ret;
1792}
1793
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001794status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1795 if (offlineClient.get() == nullptr) {
1796 return BAD_VALUE;
1797 }
1798
1799 {
1800 // Acquire mServiceLock and prevent other clients from connecting
1801 std::unique_ptr<AutoConditionLock> lock =
1802 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1803
1804 if (lock == nullptr) {
1805 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1806 , __FUNCTION__, offlineClient->getClientPid());
1807 return TIMED_OUT;
1808 }
1809
1810 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1811 if (onlineClientDesc.get() == nullptr) {
1812 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1813 cameraId.c_str());
1814 return BAD_VALUE;
1815 }
1816
1817 // Offline clients do not evict or conflict with other online devices. Resource sharing
1818 // conflicts are handled by the camera provider which will either succeed or fail before
1819 // reaching this method.
1820 const auto& onlinePriority = onlineClientDesc->getPriority();
1821 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1822 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1823 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1824 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1825
1826 // Allow only one offline device per camera
1827 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1828 if (!incompatibleClients.empty()) {
1829 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1830 return BAD_VALUE;
1831 }
1832
1833 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1834 if (err != OK) {
1835 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1836 return err;
1837 }
1838
1839 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1840 if (evicted.size() > 0) {
1841 for (auto& i : evicted) {
1842 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1843 __FUNCTION__, i->getKey().string());
1844 }
1845
1846 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1847 "properly", __FUNCTION__);
1848
1849 return BAD_VALUE;
1850 }
1851
1852 logConnectedOffline(offlineClientDesc->getKey(),
1853 static_cast<int>(offlineClientDesc->getOwnerId()),
1854 String8(offlineClient->getPackageName()));
1855
1856 sp<IBinder> remoteCallback = offlineClient->getRemote();
1857 if (remoteCallback != nullptr) {
1858 remoteCallback->linkToDeath(this);
1859 }
1860 } // lock is destroyed, allow further connect calls
1861
1862 return OK;
1863}
1864
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001865Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001866 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001867 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001868
1869 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001870 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001871 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001872 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1873 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001874 }
1875
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001876 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001877 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001878
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -07001879 if (shouldRejectSystemCameraConnection(id)) {
1880 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
1881 " for system only device %s: ", id.string());
1882 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001883 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001884 auto state = getCameraState(id);
1885 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001886 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001887 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1888 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001889 }
1890
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001891 StatusInternal cameraStatus = state->getStatus();
1892 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001893 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1894 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001895 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1896 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001897 }
1898
1899 {
1900 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001901 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001902 status_t err = getTorchStatusLocked(id, &status);
1903 if (err != OK) {
1904 if (err == NAME_NOT_FOUND) {
1905 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1906 "Camera \"%s\" does not have a flash unit", id.string());
1907 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001908 ALOGE("%s: getting current torch status failed for camera %s",
1909 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001910 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1911 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1912 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001913 }
1914
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001915 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001916 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001917 ALOGE("%s: torch mode of camera %s is not available because "
1918 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001919 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1920 "Torch for camera \"%s\" is not available due to an existing camera user",
1921 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001922 } else {
1923 ALOGE("%s: torch mode of camera %s is not available due to "
1924 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001925 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1926 "Torch for camera \"%s\" is not available due to insufficient resources",
1927 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001928 }
1929 }
1930 }
1931
Ruben Brunk99e69712015-05-26 17:25:07 -07001932 {
1933 // Update UID map - this is used in the torch status changed callbacks, so must be done
1934 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001935 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001936 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1937 mTorchUidMap[id].first = uid;
1938 mTorchUidMap[id].second = uid;
1939 } else {
1940 // Set the pending UID
1941 mTorchUidMap[id].first = uid;
1942 }
1943 }
1944
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001945 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001946
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001947 if (err != OK) {
1948 int32_t errorCode;
1949 String8 msg;
1950 switch (err) {
1951 case -ENOSYS:
1952 msg = String8::format("Camera \"%s\" has no flashlight",
1953 id.string());
1954 errorCode = ERROR_ILLEGAL_ARGUMENT;
1955 break;
1956 default:
1957 msg = String8::format(
1958 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1959 id.string(), enabled, strerror(-err), err);
1960 errorCode = ERROR_INVALID_OPERATION;
1961 }
1962 ALOGE("%s: %s", __FUNCTION__, msg.string());
1963 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001964 }
1965
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001966 {
1967 // update the link to client's death
1968 Mutex::Autolock al(mTorchClientMapMutex);
1969 ssize_t index = mTorchClientMap.indexOfKey(id);
1970 if (enabled) {
1971 if (index == NAME_NOT_FOUND) {
1972 mTorchClientMap.add(id, clientBinder);
1973 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001974 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001975 mTorchClientMap.replaceValueAt(index, clientBinder);
1976 }
1977 clientBinder->linkToDeath(this);
1978 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001979 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001980 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001981 }
1982
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001983 int clientPid = CameraThreadState::getCallingPid();
1984 const char *id_cstr = id.c_str();
1985 const char *torchState = enabled ? "on" : "off";
1986 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1987 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001988 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001989}
1990
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001991Status CameraService::notifySystemEvent(int32_t eventId,
1992 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001993 const int pid = CameraThreadState::getCallingPid();
1994 const int selfPid = getpid();
1995
1996 // Permission checks
1997 if (pid != selfPid) {
1998 // Ensure we're being called by system_server, or similar process with
1999 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002000 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002001 const int uid = CameraThreadState::getCallingUid();
2002 ALOGE("Permission Denial: cannot send updates to camera service about system"
2003 " events from pid=%d, uid=%d", pid, uid);
2004 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002005 "No permission to send updates to camera service about system events"
2006 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002007 }
2008 }
2009
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002010 ATRACE_CALL();
2011
Ruben Brunk36597b22015-03-20 22:15:57 -07002012 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002013 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002014 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002015 // from a system server crash
2016 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002017 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002018 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002019 break;
2020 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002021 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002022 default: {
2023 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2024 eventId);
2025 break;
2026 }
2027 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002028 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002029}
2030
Emilian Peev53722fa2019-02-22 17:47:20 -08002031void CameraService::notifyMonitoredUids() {
2032 Mutex::Autolock lock(mStatusListenerLock);
2033
2034 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002035 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002036 if (!ret.isOk()) {
2037 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2038 ret.exceptionCode());
2039 }
2040 }
2041}
2042
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002043Status CameraService::notifyDeviceStateChange(int64_t newState) {
2044 const int pid = CameraThreadState::getCallingPid();
2045 const int selfPid = getpid();
2046
2047 // Permission checks
2048 if (pid != selfPid) {
2049 // Ensure we're being called by system_server, or similar process with
2050 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002051 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002052 const int uid = CameraThreadState::getCallingUid();
2053 ALOGE("Permission Denial: cannot send updates to camera service about device"
2054 " state changes from pid=%d, uid=%d", pid, uid);
2055 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2056 "No permission to send updates to camera service about device state"
2057 " changes from pid=%d, uid=%d", pid, uid);
2058 }
2059 }
2060
2061 ATRACE_CALL();
2062
2063 using hardware::camera::provider::V2_5::DeviceState;
2064 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2065 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2066 newDeviceState |= DeviceState::BACK_COVERED;
2067 }
2068 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2069 newDeviceState |= DeviceState::FRONT_COVERED;
2070 }
2071 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2072 newDeviceState |= DeviceState::FOLDED;
2073 }
2074 // Only map vendor bits directly
2075 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2076 newDeviceState |= vendorBits;
2077
2078 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2079 Mutex::Autolock l(mServiceLock);
2080 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2081
2082 return Status::ok();
2083}
2084
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002085 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002086 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2087 ATRACE_CALL();
2088 if (!concurrentCameraIds) {
2089 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2090 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2091 }
2092
2093 if (!mInitialized) {
2094 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2095 return STATUS_ERROR(ERROR_DISCONNECTED,
2096 "Camera subsystem is not available");
2097 }
2098 // First call into the provider and get the set of concurrent camera
2099 // combinations
2100 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002101 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002102 for (auto &combination : concurrentCameraCombinations) {
2103 std::vector<std::string> validCombination;
2104 for (auto &cameraId : combination) {
2105 // if the camera state is not present, skip
2106 String8 cameraIdStr(cameraId.c_str());
2107 auto state = getCameraState(cameraIdStr);
2108 if (state == nullptr) {
2109 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2110 continue;
2111 }
2112 StatusInternal status = state->getStatus();
2113 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2114 continue;
2115 }
2116 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2117 continue;
2118 }
2119 validCombination.push_back(cameraId);
2120 }
2121 if (validCombination.size() != 0) {
2122 concurrentCameraIds->push_back(std::move(validCombination));
2123 }
2124 }
2125 return Status::ok();
2126}
2127
2128Status CameraService::isConcurrentSessionConfigurationSupported(
2129 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2130 /*out*/bool* isSupported) {
2131 if (!isSupported) {
2132 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2133 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2134 }
2135
2136 if (!mInitialized) {
2137 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2138 return STATUS_ERROR(ERROR_DISCONNECTED,
2139 "Camera subsystem is not available");
2140 }
2141
2142 // Check for camera permissions
2143 int callingPid = CameraThreadState::getCallingPid();
2144 int callingUid = CameraThreadState::getCallingUid();
2145 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2146 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2147 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2148 "android.permission.CAMERA needed to call"
2149 "isConcurrentSessionConfigurationSupported");
2150 }
2151
2152 status_t res =
2153 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2154 cameraIdsAndSessionConfigurations, isSupported);
2155 if (res != OK) {
2156 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2157 "support %s (%d)", strerror(-res), res);
2158 }
2159 return Status::ok();
2160}
2161
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002162Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2163 /*out*/
2164 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002165 return addListenerHelper(listener, cameraStatuses);
2166}
2167
2168Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2169 /*out*/
2170 std::vector<hardware::CameraStatus> *cameraStatuses,
2171 bool isVendorListener) {
2172
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002173 ATRACE_CALL();
2174
Igor Murashkinbfc99152013-02-27 12:55:20 -08002175 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002176
Ruben Brunk3450ba72015-06-16 11:00:37 -07002177 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002178 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002180 }
2181
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002182 auto clientUid = CameraThreadState::getCallingUid();
2183 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002184 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2185 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002186
Igor Murashkinbfc99152013-02-27 12:55:20 -08002187 Mutex::Autolock lock(mServiceLock);
2188
Ruben Brunkcc776712015-02-17 20:18:47 -08002189 {
2190 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002191 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002192 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 ALOGW("%s: Tried to add listener %p which was already subscribed",
2194 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002195 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002196 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002197 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002198
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002199 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002200 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2201 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002202 auto ret = serviceListener->initialize();
2203 if (ret != NO_ERROR) {
2204 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2205 strerror(-ret), ret);
2206 ALOGE("%s: %s", __FUNCTION__, msg.string());
2207 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2208 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002209 // The listener still needs to be added to the list of listeners, regardless of what
2210 // permissions the listener process has / whether it is a vendor listener. Since it might be
2211 // eligible to listen to other camera ids.
2212 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002213 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002214 }
2215
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002216 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002217 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002218 Mutex::Autolock lock(mCameraStatesLock);
2219 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002220 cameraStatuses->emplace_back(i.first,
2221 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002222 }
2223 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002224 // Remove the camera statuses that should be hidden from the client, we do
2225 // this after collecting the states in order to avoid holding
2226 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2227 // the same time.
2228 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2229 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2230 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2231 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2232 ALOGE("%s: Invalid camera id %s, skipping status update",
2233 __FUNCTION__, s.cameraId.c_str());
2234 return true;
2235 }
2236 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2237 clientUid);}), cameraStatuses->end());
2238
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -07002239 //cameraStatuses will have non-eligible camera ids removed.
2240 std::set<String16> idsChosenForCallback;
2241 for (const auto &s : *cameraStatuses) {
2242 idsChosenForCallback.insert(String16(s.cameraId));
2243 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002244
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002245 /*
2246 * Immediately signal current torch status to this listener only
2247 * This may be a subset of all the devices, so don't include it in the response directly
2248 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002249 {
2250 Mutex::Autolock al(mTorchStatusMutex);
2251 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002252 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -07002253 // The camera id is visible to the client. Fine to send torch
2254 // callback.
2255 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2256 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2257 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002258 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002259 }
2260
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002261 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002262}
Ruben Brunkcc776712015-02-17 20:18:47 -08002263
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002264Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002265 ATRACE_CALL();
2266
Igor Murashkinbfc99152013-02-27 12:55:20 -08002267 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2268
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002269 if (listener == 0) {
2270 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002271 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002272 }
2273
Igor Murashkinbfc99152013-02-27 12:55:20 -08002274 Mutex::Autolock lock(mServiceLock);
2275
Ruben Brunkcc776712015-02-17 20:18:47 -08002276 {
2277 Mutex::Autolock lock(mStatusListenerLock);
2278 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002279 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2280 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2281 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002282 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002283 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002284 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002285 }
2286 }
2287
2288 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2289 __FUNCTION__, listener.get());
2290
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002292}
2293
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002294Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002295
2296 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002297 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2298
2299 if (parameters == NULL) {
2300 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002301 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002302 }
2303
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002304 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002305
2306 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002307 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002308 // Error logged by caller
2309 return ret;
2310 }
2311
2312 String8 shimParamsString8 = shimParams.flatten();
2313 String16 shimParamsString16 = String16(shimParamsString8);
2314
2315 *parameters = shimParamsString16;
2316
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002317 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002318}
2319
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002320Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2321 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002322 ATRACE_CALL();
2323
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002324 const String8 id = String8(cameraId);
2325
2326 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002327
2328 switch (apiVersion) {
2329 case API_VERSION_1:
2330 case API_VERSION_2:
2331 break;
2332 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 String8 msg = String8::format("Unknown API version %d", apiVersion);
2334 ALOGE("%s: %s", __FUNCTION__, msg.string());
2335 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002336 }
2337
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002338 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002339 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002340 case CAMERA_DEVICE_API_VERSION_1_0:
2341 case CAMERA_DEVICE_API_VERSION_3_0:
2342 case CAMERA_DEVICE_API_VERSION_3_1:
2343 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002344 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2345 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002346 *isSupported = false;
2347 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002348 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2349 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 *isSupported = true;
2351 }
2352 break;
2353 case CAMERA_DEVICE_API_VERSION_3_2:
2354 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002355 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002356 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002357 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002358 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2359 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002360 *isSupported = true;
2361 break;
2362 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002363 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002364 ALOGE("%s: %s", __FUNCTION__, msg.string());
2365 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002366 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002367 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002368 String8 msg = String8::format("Unknown device version %x for device %s",
2369 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002370 ALOGE("%s: %s", __FUNCTION__, msg.string());
2371 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2372 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002373 }
2374
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002375 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002376}
2377
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002378Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2379 /*out*/ bool *isSupported) {
2380 ATRACE_CALL();
2381
2382 const String8 id = String8(cameraId);
2383
2384 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2385 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2386
2387 return Status::ok();
2388}
2389
Ruben Brunkcc776712015-02-17 20:18:47 -08002390void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002391 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002392 for (auto& i : mActiveClientManager.getAll()) {
2393 auto clientSp = i->getValue();
2394 if (clientSp.get() == client) {
2395 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002396 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002397 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002398 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002399}
2400
Ruben Brunkcc776712015-02-17 20:18:47 -08002401bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002402 bool ret = false;
2403 {
2404 // Acquire mServiceLock and prevent other clients from connecting
2405 std::unique_ptr<AutoConditionLock> lock =
2406 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002407
Igor Murashkin634a5152013-02-20 17:15:11 -08002408
Ruben Brunkcc776712015-02-17 20:18:47 -08002409 std::vector<sp<BasicClient>> evicted;
2410 for (auto& i : mActiveClientManager.getAll()) {
2411 auto clientSp = i->getValue();
2412 if (clientSp.get() == nullptr) {
2413 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2414 mActiveClientManager.remove(i);
2415 continue;
2416 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002417 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002418 mActiveClientManager.remove(i);
2419 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002420
Ruben Brunkcc776712015-02-17 20:18:47 -08002421 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002422 clientSp->notifyError(
2423 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002424 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002425 }
2426 }
2427
Ruben Brunkcc776712015-02-17 20:18:47 -08002428 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2429 // other clients from connecting in mServiceLockWrapper if held
2430 mServiceLock.unlock();
2431
Ruben Brunk36597b22015-03-20 22:15:57 -07002432 // Do not clear caller identity, remote caller should be client proccess
2433
Ruben Brunkcc776712015-02-17 20:18:47 -08002434 for (auto& i : evicted) {
2435 if (i.get() != nullptr) {
2436 i->disconnect();
2437 ret = true;
2438 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002439 }
2440
Ruben Brunkcc776712015-02-17 20:18:47 -08002441 // Reacquire mServiceLock
2442 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002443
Ruben Brunkcc776712015-02-17 20:18:47 -08002444 } // lock is destroyed, allow further connect calls
2445
2446 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002447}
2448
Ruben Brunkcc776712015-02-17 20:18:47 -08002449std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2450 const String8& cameraId) const {
2451 std::shared_ptr<CameraState> state;
2452 {
2453 Mutex::Autolock lock(mCameraStatesLock);
2454 auto iter = mCameraStates.find(cameraId);
2455 if (iter != mCameraStates.end()) {
2456 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 }
2458 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002459 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460}
2461
Ruben Brunkcc776712015-02-17 20:18:47 -08002462sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2463 // Remove from active clients list
2464 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2465 if (clientDescriptorPtr == nullptr) {
2466 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2467 cameraId.string());
2468 return sp<BasicClient>{nullptr};
2469 }
2470
2471 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002472}
2473
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002474void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002475 // Acquire mServiceLock and prevent other clients from connecting
2476 std::unique_ptr<AutoConditionLock> lock =
2477 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2478
Ruben Brunk6267b532015-04-30 17:44:07 -07002479 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002480 for (size_t i = 0; i < newUserIds.size(); i++) {
2481 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002482 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002483 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002484 return;
2485 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002486 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002487 }
2488
Ruben Brunka8ca9152015-04-07 14:23:40 -07002489
Ruben Brunk6267b532015-04-30 17:44:07 -07002490 if (newAllowedUsers == mAllowedUsers) {
2491 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2492 return;
2493 }
2494
2495 logUserSwitch(mAllowedUsers, newAllowedUsers);
2496
2497 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002498
2499 // Current user has switched, evict all current clients.
2500 std::vector<sp<BasicClient>> evicted;
2501 for (auto& i : mActiveClientManager.getAll()) {
2502 auto clientSp = i->getValue();
2503
2504 if (clientSp.get() == nullptr) {
2505 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2506 continue;
2507 }
2508
Ruben Brunk6267b532015-04-30 17:44:07 -07002509 // Don't evict clients that are still allowed.
2510 uid_t clientUid = clientSp->getClientUid();
2511 userid_t clientUserId = multiuser_get_user_id(clientUid);
2512 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2513 continue;
2514 }
2515
Ruben Brunk36597b22015-03-20 22:15:57 -07002516 evicted.push_back(clientSp);
2517
2518 String8 curTime = getFormattedCurrentTime();
2519
2520 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2521 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002522
Ruben Brunk36597b22015-03-20 22:15:57 -07002523 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002524 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002525 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2526 " to user switch.", i->getKey().string(),
2527 String8{clientSp->getPackageName()}.string(),
2528 i->getOwnerId(), i->getPriority().getScore(),
2529 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002530
2531 }
2532
2533 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2534 // blocking other clients from connecting in mServiceLockWrapper if held.
2535 mServiceLock.unlock();
2536
2537 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002538 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002539
2540 for (auto& i : evicted) {
2541 i->disconnect();
2542 }
2543
Jayant Chowdhary12361932018-08-27 14:46:13 -07002544 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002545
2546 // Reacquire mServiceLock
2547 mServiceLock.lock();
2548}
Ruben Brunkcc776712015-02-17 20:18:47 -08002549
Ruben Brunka8ca9152015-04-07 14:23:40 -07002550void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002551 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002552 Mutex::Autolock l(mLogLock);
2553 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554}
2555
Ruben Brunka8ca9152015-04-07 14:23:40 -07002556void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002557 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002558 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002559 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002560 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002561}
2562
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002563void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2564 const char* clientPackage) {
2565 // Log the clients evicted
2566 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2567 cameraId, clientPackage, clientPid));
2568}
2569
Ruben Brunka8ca9152015-04-07 14:23:40 -07002570void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002571 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002572 // Log the clients evicted
2573 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002574 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002575}
2576
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002577void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2578 const char* clientPackage) {
2579 // Log the clients evicted
2580 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2581 clientPackage, clientPid));
2582}
2583
Ruben Brunka8ca9152015-04-07 14:23:40 -07002584void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002585 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002586 // Log the client rejected
2587 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002588 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002589}
2590
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002591void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2592 // Log torch event
2593 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2594 torchState, clientPid));
2595}
2596
Ruben Brunk6267b532015-04-30 17:44:07 -07002597void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2598 const std::set<userid_t>& newUserIds) {
2599 String8 newUsers = toString(newUserIds);
2600 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002601 if (oldUsers.size() == 0) {
2602 oldUsers = "<None>";
2603 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002604 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002605 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002606 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002607}
2608
2609void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2610 // Log the device removal
2611 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2612}
2613
2614void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2615 // Log the device removal
2616 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2617}
2618
2619void CameraService::logClientDied(int clientPid, const char* reason) {
2620 // Log the device removal
2621 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002622}
2623
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002624void CameraService::logServiceError(const char* msg, int errorCode) {
2625 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002626 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002627}
2628
Ruben Brunk36597b22015-03-20 22:15:57 -07002629status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2630 uint32_t flags) {
2631
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 // Permission checks
2633 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002634 case SHELL_COMMAND_TRANSACTION: {
2635 int in = data.readFileDescriptor();
2636 int out = data.readFileDescriptor();
2637 int err = data.readFileDescriptor();
2638 int argc = data.readInt32();
2639 Vector<String16> args;
2640 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2641 args.add(data.readString16());
2642 }
2643 sp<IBinder> unusedCallback;
2644 sp<IResultReceiver> resultReceiver;
2645 status_t status;
2646 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2647 return status;
2648 }
2649 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2650 return status;
2651 }
2652 status = shellCommand(in, out, err, args);
2653 if (resultReceiver != nullptr) {
2654 resultReceiver->send(status);
2655 }
2656 return NO_ERROR;
2657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658 }
2659
2660 return BnCameraService::onTransact(code, data, reply, flags);
2661}
2662
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663// We share the media players for shutter and recording sound for all clients.
2664// A reference count is kept to determine when we will actually release the
2665// media players.
2666
Jaekyun Seokef498052018-03-23 13:09:44 +09002667sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2668 sp<MediaPlayer> mp = new MediaPlayer();
2669 status_t error;
2670 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002671 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002672 error = mp->prepare();
2673 }
2674 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002675 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002676 mp->disconnect();
2677 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002678 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 }
2680 return mp;
2681}
2682
username5755fea2018-12-27 09:48:08 +08002683void CameraService::increaseSoundRef() {
2684 Mutex::Autolock lock(mSoundLock);
2685 mSoundRef++;
2686}
2687
2688void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002689 ATRACE_CALL();
2690
username5755fea2018-12-27 09:48:08 +08002691 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2692 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2693 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2694 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2695 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2696 }
2697 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2698 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2699 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2700 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002701 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002702 }
2703 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2704 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2705 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2706 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2707 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002708 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709}
2710
username5755fea2018-12-27 09:48:08 +08002711void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002713 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714 if (--mSoundRef) return;
2715
2716 for (int i = 0; i < NUM_SOUNDS; i++) {
2717 if (mSoundPlayer[i] != 0) {
2718 mSoundPlayer[i]->disconnect();
2719 mSoundPlayer[i].clear();
2720 }
2721 }
2722}
2723
2724void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002725 ATRACE_CALL();
2726
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 LOG1("playSound(%d)", kind);
2728 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002729 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 sp<MediaPlayer> player = mSoundPlayer[kind];
2731 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002732 player->seekTo(0);
2733 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734 }
2735}
2736
2737// ----------------------------------------------------------------------------
2738
2739CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002740 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002741 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002742 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002743 const String8& cameraIdStr,
2744 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002745 int clientPid, uid_t clientUid,
2746 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002747 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002748 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002749 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002750 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002751 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002752 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002753 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002754{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002755 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002756 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002758 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759
username5755fea2018-12-27 09:48:08 +08002760 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002761
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002762 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763}
2764
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765// tear down the client
2766CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002767 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002768 mDestructionStarted = true;
2769
username5755fea2018-12-27 09:48:08 +08002770 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002771 // unconditionally disconnect. function is idempotent
2772 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773}
2774
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002775sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2776
Igor Murashkin634a5152013-02-20 17:15:11 -08002777CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002778 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002779 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002780 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002781 int clientPid, uid_t clientUid,
2782 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002783 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002784 mClientPackageName(clientPackageName),
2785 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002786 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002787 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002788 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002789 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002790{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002791 if (clientFeatureId) {
2792 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2793 } else {
2794 mClientFeatureId = std::unique_ptr<String16>();
2795 }
2796
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002797 if (sCameraService == nullptr) {
2798 sCameraService = cameraService;
2799 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002800 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002801 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002802
2803 // In some cases the calling code has no access to the package it runs under.
2804 // For example, NDK camera API.
2805 // In this case we will get the packages for the calling UID and pick the first one
2806 // for attributing the app op. This will work correctly for runtime permissions
2807 // as for legacy apps we will toggle the app op for all packages in the UID.
2808 // The caveat is that the operation may be attributed to the wrong package and
2809 // stats based on app ops may be slightly off.
2810 if (mClientPackageName.size() <= 0) {
2811 sp<IServiceManager> sm = defaultServiceManager();
2812 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2813 if (binder == 0) {
2814 ALOGE("Cannot get permission service");
2815 // Leave mClientPackageName unchanged (empty) and the further interaction
2816 // with camera will fail in BasicClient::startCameraOps
2817 return;
2818 }
2819
2820 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2821 Vector<String16> packages;
2822
2823 permCtrl->getPackagesForUid(mClientUid, packages);
2824
2825 if (packages.isEmpty()) {
2826 ALOGE("No packages for calling UID");
2827 // Leave mClientPackageName unchanged (empty) and the further interaction
2828 // with camera will fail in BasicClient::startCameraOps
2829 return;
2830 }
2831 mClientPackageName = packages[0];
2832 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002833 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002834 mAppOpsManager = std::make_unique<AppOpsManager>();
2835 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002836
2837 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002838}
2839
2840CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002841 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002842 mDestructionStarted = true;
2843}
2844
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002845binder::Status CameraService::BasicClient::disconnect() {
2846 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002847 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002848 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002849 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002850 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002851
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002852 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002853 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002854 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2855 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002856
2857 sp<IBinder> remote = getRemote();
2858 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002859 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002860 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002861
2862 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002863 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002864 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2865 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2866 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002867
Igor Murashkincba2c162013-03-20 15:56:31 -07002868 // client shouldn't be able to call into us anymore
2869 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002870
2871 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002872}
2873
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002874status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2875 // No dumping of clients directly over Binder,
2876 // must go through CameraService::dump
2877 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002878 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002879 return OK;
2880}
2881
Ruben Brunkcc776712015-02-17 20:18:47 -08002882String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002883 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002884}
2885
2886
2887int CameraService::BasicClient::getClientPid() const {
2888 return mClientPid;
2889}
2890
Ruben Brunk6267b532015-04-30 17:44:07 -07002891uid_t CameraService::BasicClient::getClientUid() const {
2892 return mClientUid;
2893}
2894
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002895bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2896 // Defaults to API2.
2897 return level == API_2;
2898}
2899
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002900status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002901 {
2902 Mutex::Autolock l(mAudioRestrictionLock);
2903 mAudioRestriction = mode;
2904 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002905 sCameraService->updateAudioRestriction();
2906 return OK;
2907}
2908
2909int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002910 return sCameraService->updateAudioRestriction();
2911}
2912
2913int32_t CameraService::BasicClient::getAudioRestriction() const {
2914 Mutex::Autolock l(mAudioRestrictionLock);
2915 return mAudioRestriction;
2916}
2917
2918bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2919 switch (mode) {
2920 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2921 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2922 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2923 return true;
2924 default:
2925 return false;
2926 }
2927}
2928
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002929status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002930 ATRACE_CALL();
2931
Igor Murashkine6800ce2013-03-04 17:25:57 -08002932 {
2933 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002934 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002935 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002936 if (mAppOpsManager != nullptr) {
2937 // Notify app ops that the camera is not available
2938 mOpsCallback = new OpsCallback(this);
2939 int32_t res;
2940 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2941 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002942 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2943 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2944 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002945
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002946 if (res == AppOpsManager::MODE_ERRORED) {
2947 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2948 mCameraIdStr.string(), String8(mClientPackageName).string());
2949 return PERMISSION_DENIED;
2950 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002951
Shuzhen Wang2c656792020-04-13 17:36:49 -07002952 // If the calling Uid is trusted (a native service), the AppOpsManager could
2953 // return MODE_IGNORED. Do not treat such case as error.
2954 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002955 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2956 mCameraIdStr.string(), String8(mClientPackageName).string());
2957 // Return the same error as for device policy manager rejection
2958 return -EACCES;
2959 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002960 }
2961
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002962 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002963
2964 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002965 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002966
Emilian Peev573291c2018-02-10 02:10:56 +00002967 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2968 if (canCastToApiClient(API_2)) {
2969 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2970 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002971 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002972 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002973 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002974
Emilian Peev53722fa2019-02-22 17:47:20 -08002975 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2976
Shuzhen Wang695044d2020-03-06 09:02:23 -08002977 // Notify listeners of camera open/close status
2978 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2979
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002980 return OK;
2981}
2982
2983status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002984 ATRACE_CALL();
2985
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002986 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002987 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002988 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002989 if (mAppOpsManager != nullptr) {
2990 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002991 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002992 mOpsActive = false;
2993 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002994 // This function is called when a client disconnects. This should
2995 // release the camera, but actually only if it was in a proper
2996 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002997 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002998 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002999
Ruben Brunkcc776712015-02-17 20:18:47 -08003000 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003001 sCameraService->updateStatus(StatusInternal::PRESENT,
3002 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003003
Emilian Peev573291c2018-02-10 02:10:56 +00003004 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
3005 if (canCastToApiClient(API_2)) {
3006 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
3007 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003008 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003009 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00003010 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003011 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003012 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003013 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3014 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003015 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003016 mOpsCallback.clear();
3017
Emilian Peev53722fa2019-02-22 17:47:20 -08003018 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3019
Shuzhen Wang695044d2020-03-06 09:02:23 -08003020 // Notify listeners of camera open/close status
3021 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3022
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003023 return OK;
3024}
3025
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003026void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003027 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003028 if (mAppOpsManager == nullptr) {
3029 return;
3030 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003031 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003032 if (op != AppOpsManager::OP_CAMERA) {
3033 ALOGW("Unexpected app ops notification received: %d", op);
3034 return;
3035 }
3036
3037 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003038 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003039 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003040 ALOGV("checkOp returns: %d, %s ", res,
3041 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3042 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3043 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3044 "UNKNOWN");
3045
3046 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003047 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003048 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003049 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003050 }
3051}
3052
Svet Ganova453d0d2018-01-11 15:37:58 -08003053void CameraService::BasicClient::block() {
3054 ATRACE_CALL();
3055
3056 // Reset the client PID to allow server-initiated disconnect,
3057 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003058 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003059 CaptureResultExtras resultExtras; // a dummy result (invalid)
3060 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3061 disconnect();
3062}
3063
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064// ----------------------------------------------------------------------------
3065
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003066void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003067 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003068 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003069 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003070 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3071 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3072 api1ErrorCode = CAMERA_ERROR_DISABLED;
3073 }
3074 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003075 } else {
3076 ALOGE("mRemoteCallback is NULL!!");
3077 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003078}
3079
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003080// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003081binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003082 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003083 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003084}
3085
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003086bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3087 return level == API_1;
3088}
3089
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003090CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3091 mClient(client) {
3092}
3093
3094void CameraService::Client::OpsCallback::opChanged(int32_t op,
3095 const String16& packageName) {
3096 sp<BasicClient> client = mClient.promote();
3097 if (client != NULL) {
3098 client->opChanged(op, packageName);
3099 }
3100}
3101
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003103// UidPolicy
3104// ----------------------------------------------------------------------------
3105
3106void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003107 Mutex::Autolock _l(mUidLock);
3108
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003109 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003110 status_t res = mAm.linkToDeath(this);
3111 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003112 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003113 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003114 ActivityManager::PROCESS_STATE_UNKNOWN,
3115 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003116 if (res == OK) {
3117 mRegistered = true;
3118 ALOGV("UidPolicy: Registered with ActivityManager");
3119 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003120}
3121
3122void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003123 Mutex::Autolock _l(mUidLock);
3124
Steven Moreland2f348142019-07-02 15:59:07 -07003125 mAm.unregisterUidObserver(this);
3126 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003127 mRegistered = false;
3128 mActiveUids.clear();
3129 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003130}
3131
3132void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3133 onUidIdle(uid, disabled);
3134}
3135
3136void CameraService::UidPolicy::onUidActive(uid_t uid) {
3137 Mutex::Autolock _l(mUidLock);
3138 mActiveUids.insert(uid);
3139}
3140
3141void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3142 bool deleted = false;
3143 {
3144 Mutex::Autolock _l(mUidLock);
3145 if (mActiveUids.erase(uid) > 0) {
3146 deleted = true;
3147 }
3148 }
3149 if (deleted) {
3150 sp<CameraService> service = mService.promote();
3151 if (service != nullptr) {
3152 service->blockClientsForUid(uid);
3153 }
3154 }
3155}
3156
Emilian Peev53722fa2019-02-22 17:47:20 -08003157void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003158 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003159 bool procStateChange = false;
3160 {
3161 Mutex::Autolock _l(mUidLock);
3162 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3163 (mMonitoredUids[uid].first != procState)) {
3164 mMonitoredUids[uid].first = procState;
3165 procStateChange = true;
3166 }
3167 }
3168
3169 if (procStateChange) {
3170 sp<CameraService> service = mService.promote();
3171 if (service != nullptr) {
3172 service->notifyMonitoredUids();
3173 }
3174 }
3175}
3176
3177void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3178 Mutex::Autolock _l(mUidLock);
3179 auto it = mMonitoredUids.find(uid);
3180 if (it != mMonitoredUids.end()) {
3181 it->second.second++;
3182 } else {
3183 mMonitoredUids.emplace(
3184 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3185 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3186 }
3187}
3188
3189void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3190 Mutex::Autolock _l(mUidLock);
3191 auto it = mMonitoredUids.find(uid);
3192 if (it != mMonitoredUids.end()) {
3193 it->second.second--;
3194 if (it->second.second == 0) {
3195 mMonitoredUids.erase(it);
3196 }
3197 } else {
3198 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3199 }
3200}
3201
Svet Ganov7b4ab782018-03-25 12:48:10 -07003202bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003203 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003204 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003205}
3206
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003207static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3208static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003209
Svet Ganov7b4ab782018-03-25 12:48:10 -07003210bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003211 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003212 // If activity manager is unreachable, assume everything is active
3213 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003214 return true;
3215 }
3216 auto it = mOverrideUids.find(uid);
3217 if (it != mOverrideUids.end()) {
3218 return it->second;
3219 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003220 bool active = mActiveUids.find(uid) != mActiveUids.end();
3221 if (!active) {
3222 // We want active UIDs to always access camera with their first attempt since
3223 // there is no guarantee the app is robustly written and would retry getting
3224 // the camera on failure. The inverse case is not a problem as we would take
3225 // camera away soon once we get the callback that the uid is no longer active.
3226 ActivityManager am;
3227 // Okay to access with a lock held as UID changes are dispatched without
3228 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003229 int64_t startTimeMillis = 0;
3230 do {
3231 // TODO: Fix this b/109950150!
3232 // Okay this is a hack. There is a race between the UID turning active and
3233 // activity being resumed. The proper fix is very risky, so we temporary add
3234 // some polling which should happen pretty rarely anyway as the race is hard
3235 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003236 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003237 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003238 if (active) {
3239 break;
3240 }
3241 if (startTimeMillis <= 0) {
3242 startTimeMillis = uptimeMillis();
3243 }
3244 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003245 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003246 if (remainingTimeMillis <= 0) {
3247 break;
3248 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003249 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3250
3251 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003252 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003253 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003254 } while (true);
3255
Svet Ganov7b4ab782018-03-25 12:48:10 -07003256 if (active) {
3257 // Now that we found out the UID is actually active, cache that
3258 mActiveUids.insert(uid);
3259 }
3260 }
3261 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003262}
3263
Varun Shahb42f1eb2019-04-16 14:45:13 -07003264int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3265 Mutex::Autolock _l(mUidLock);
3266 return getProcStateLocked(uid);
3267}
3268
3269int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3270 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3271 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3272 procState = mMonitoredUids[uid].first;
3273 }
3274 return procState;
3275}
3276
Svet Ganov7b4ab782018-03-25 12:48:10 -07003277void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3278 String16 callingPackage, bool active) {
3279 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003280}
3281
Svet Ganov7b4ab782018-03-25 12:48:10 -07003282void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3283 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003284}
3285
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003286void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3287 Mutex::Autolock _l(mUidLock);
3288 ALOGV("UidPolicy: ActivityManager has died");
3289 mRegistered = false;
3290 mActiveUids.clear();
3291}
3292
Svet Ganov7b4ab782018-03-25 12:48:10 -07003293void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3294 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003295 bool wasActive = false;
3296 bool isActive = false;
3297 {
3298 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003299 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003300 mOverrideUids.erase(uid);
3301 if (insert) {
3302 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3303 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003304 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003305 }
3306 if (wasActive != isActive && !isActive) {
3307 sp<CameraService> service = mService.promote();
3308 if (service != nullptr) {
3309 service->blockClientsForUid(uid);
3310 }
3311 }
3312}
3313
3314// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003315// SensorPrivacyPolicy
3316// ----------------------------------------------------------------------------
3317void CameraService::SensorPrivacyPolicy::registerSelf() {
3318 Mutex::Autolock _l(mSensorPrivacyLock);
3319 if (mRegistered) {
3320 return;
3321 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003322 mSpm.addSensorPrivacyListener(this);
3323 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3324 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003325 if (res == OK) {
3326 mRegistered = true;
3327 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3328 }
3329}
3330
3331void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3332 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003333 mSpm.removeSensorPrivacyListener(this);
3334 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003335 mRegistered = false;
3336 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3337}
3338
3339bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3340 Mutex::Autolock _l(mSensorPrivacyLock);
3341 return mSensorPrivacyEnabled;
3342}
3343
3344binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3345 {
3346 Mutex::Autolock _l(mSensorPrivacyLock);
3347 mSensorPrivacyEnabled = enabled;
3348 }
3349 // if sensor privacy is enabled then block all clients from accessing the camera
3350 if (enabled) {
3351 sp<CameraService> service = mService.promote();
3352 if (service != nullptr) {
3353 service->blockAllClients();
3354 }
3355 }
3356 return binder::Status::ok();
3357}
3358
3359void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3360 Mutex::Autolock _l(mSensorPrivacyLock);
3361 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3362 mRegistered = false;
3363}
3364
3365// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003366// CameraState
3367// ----------------------------------------------------------------------------
3368
3369CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003370 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3371 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3372 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003373
3374CameraService::CameraState::~CameraState() {}
3375
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003376CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003377 Mutex::Autolock lock(mStatusLock);
3378 return mStatus;
3379}
3380
Shuzhen Wang43858162020-01-10 13:42:15 -08003381std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3382 Mutex::Autolock lock(mStatusLock);
3383 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3384 return res;
3385}
3386
Ruben Brunkcc776712015-02-17 20:18:47 -08003387CameraParameters CameraService::CameraState::getShimParams() const {
3388 return mShimParams;
3389}
3390
3391void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3392 mShimParams = params;
3393}
3394
3395int CameraService::CameraState::getCost() const {
3396 return mCost;
3397}
3398
3399std::set<String8> CameraService::CameraState::getConflicting() const {
3400 return mConflicting;
3401}
3402
3403String8 CameraService::CameraState::getId() const {
3404 return mId;
3405}
3406
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003407SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3408 return mSystemCameraKind;
3409}
3410
Shuzhen Wang43858162020-01-10 13:42:15 -08003411bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3412 Mutex::Autolock lock(mStatusLock);
3413 auto result = mUnavailablePhysicalIds.insert(physicalId);
3414 return result.second;
3415}
3416
3417bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3418 Mutex::Autolock lock(mStatusLock);
3419 auto count = mUnavailablePhysicalIds.erase(physicalId);
3420 return count > 0;
3421}
3422
Ruben Brunkcc776712015-02-17 20:18:47 -08003423// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003424// ClientEventListener
3425// ----------------------------------------------------------------------------
3426
3427void CameraService::ClientEventListener::onClientAdded(
3428 const resource_policy::ClientDescriptor<String8,
3429 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003430 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003431 if (basicClient.get() != nullptr) {
3432 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3433 notifier.noteStartCamera(descriptor.getKey(),
3434 static_cast<int>(basicClient->getClientUid()));
3435 }
3436}
3437
3438void CameraService::ClientEventListener::onClientRemoved(
3439 const resource_policy::ClientDescriptor<String8,
3440 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003441 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003442 if (basicClient.get() != nullptr) {
3443 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3444 notifier.noteStopCamera(descriptor.getKey(),
3445 static_cast<int>(basicClient->getClientUid()));
3446 }
3447}
3448
3449
3450// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003451// CameraClientManager
3452// ----------------------------------------------------------------------------
3453
Ruben Brunk99e69712015-05-26 17:25:07 -07003454CameraService::CameraClientManager::CameraClientManager() {
3455 setListener(std::make_shared<ClientEventListener>());
3456}
3457
Ruben Brunkcc776712015-02-17 20:18:47 -08003458CameraService::CameraClientManager::~CameraClientManager() {}
3459
3460sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3461 const String8& id) const {
3462 auto descriptor = get(id);
3463 if (descriptor == nullptr) {
3464 return sp<BasicClient>{nullptr};
3465 }
3466 return descriptor->getValue();
3467}
3468
3469String8 CameraService::CameraClientManager::toString() const {
3470 auto all = getAll();
3471 String8 ret("[");
3472 bool hasAny = false;
3473 for (auto& i : all) {
3474 hasAny = true;
3475 String8 key = i->getKey();
3476 int32_t cost = i->getCost();
3477 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003478 int32_t score = i->getPriority().getScore();
3479 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003480 auto conflicting = i->getConflicting();
3481 auto clientSp = i->getValue();
3482 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003483 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003484 if (clientSp.get() != nullptr) {
3485 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003486 uid_t clientUid = clientSp->getClientUid();
3487 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003488 }
Emilian Peev8131a262017-02-01 12:33:43 +00003489 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3490 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003491
Ruben Brunk6267b532015-04-30 17:44:07 -07003492 if (clientSp.get() != nullptr) {
3493 ret.appendFormat("User Id: %d, ", clientUserId);
3494 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003495 if (packageName.size() != 0) {
3496 ret.appendFormat("Client Package Name: %s", packageName.string());
3497 }
3498
3499 ret.append(", Conflicting Client Devices: {");
3500 for (auto& j : conflicting) {
3501 ret.appendFormat("%s, ", j.string());
3502 }
3503 ret.append("})");
3504 }
3505 if (hasAny) ret.append("\n");
3506 ret.append("]\n");
3507 return ret;
3508}
3509
3510CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3511 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003512 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3513 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003514
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003515 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003516 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3517 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3518
Ruben Brunkcc776712015-02-17 20:18:47 -08003519 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003520 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003521}
3522
3523CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3524 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3525 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003526 partial->getConflicting(), partial->getPriority().getScore(),
3527 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003528}
3529
3530// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531
3532static const int kDumpLockRetries = 50;
3533static const int kDumpLockSleep = 60000;
3534
3535static bool tryLock(Mutex& mutex)
3536{
3537 bool locked = false;
3538 for (int i = 0; i < kDumpLockRetries; ++i) {
3539 if (mutex.tryLock() == NO_ERROR) {
3540 locked = true;
3541 break;
3542 }
3543 usleep(kDumpLockSleep);
3544 }
3545 return locked;
3546}
3547
3548status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003549 ATRACE_CALL();
3550
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003551 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003552 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003553 CameraThreadState::getCallingPid(),
3554 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003555 return NO_ERROR;
3556 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003557 bool locked = tryLock(mServiceLock);
3558 // failed to lock - CameraService is probably deadlocked
3559 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003560 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003561 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003562
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003563 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003564 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003565
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003566 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003567 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003568
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003569 if (locked) mServiceLock.unlock();
3570 return NO_ERROR;
3571 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003572 dprintf(fd, "\n== Service global info: ==\n\n");
3573 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003574 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003575 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3576 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003577 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3578 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3579 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003580 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003581 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3582 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003583
3584 dumpEventLog(fd);
3585
3586 bool stateLocked = tryLock(mCameraStatesLock);
3587 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003588 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003589 }
3590
Emilian Peevbd8c5032018-02-14 23:05:40 +00003591 int argSize = args.size();
3592 for (int i = 0; i < argSize; i++) {
3593 if (args[i] == TagMonitor::kMonitorOption) {
3594 if (i + 1 < argSize) {
3595 mMonitorTags = String8(args[i + 1]);
3596 }
3597 break;
3598 }
3599 }
3600
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003601 for (auto& state : mCameraStates) {
3602 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003603
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003604 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003605
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003606 CameraParameters p = state.second->getShimParams();
3607 if (!p.isEmpty()) {
3608 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3609 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003610 }
3611
3612 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003613 if (clientDescriptor != nullptr) {
3614 dprintf(fd, " Device %s is open. Client instance dump:\n",
3615 cameraId.string());
3616 dprintf(fd, " Client priority score: %d state: %d\n",
3617 clientDescriptor->getPriority().getScore(),
3618 clientDescriptor->getPriority().getState());
3619 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3620
3621 auto client = clientDescriptor->getValue();
3622 dprintf(fd, " Client package: %s\n",
3623 String8(client->getPackageName()).string());
3624
3625 client->dumpClient(fd, args);
3626 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003627 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003628 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003629 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003630
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003631 }
3632
3633 if (stateLocked) mCameraStatesLock.unlock();
3634
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003635 if (locked) mServiceLock.unlock();
3636
Emilian Peevf53f66e2017-04-11 14:29:43 +01003637 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003638
3639 dprintf(fd, "\n== Vendor tags: ==\n\n");
3640
3641 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3642 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003643 sp<VendorTagDescriptorCache> cache =
3644 VendorTagDescriptorCache::getGlobalVendorTagCache();
3645 if (cache == NULL) {
3646 dprintf(fd, "No vendor tags.\n");
3647 } else {
3648 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3649 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003650 } else {
3651 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3652 }
3653
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003654 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003655 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003656 camera3::CameraTraces::dump(fd, args);
3657
3658 // Process dump arguments, if any
3659 int n = args.size();
3660 String16 verboseOption("-v");
3661 String16 unreachableOption("--unreachable");
3662 for (int i = 0; i < n; i++) {
3663 if (args[i] == verboseOption) {
3664 // change logging level
3665 if (i + 1 >= n) continue;
3666 String8 levelStr(args[i+1]);
3667 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003668 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003669 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003670 } else if (args[i] == unreachableOption) {
3671 // Dump memory analysis
3672 // TODO - should limit be an argument parameter?
3673 UnreachableMemoryInfo info;
3674 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3675 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003676 dprintf(fd, "\n== Unable to dump unreachable memory. "
3677 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003678 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003679 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003680 std::string s = info.ToString(/*log_contents*/ true);
3681 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 }
3683 }
3684 }
3685 return NO_ERROR;
3686}
3687
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003688void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003689 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003690
3691 Mutex::Autolock l(mLogLock);
3692 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003693 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003694 }
3695
3696 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003697 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003698 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003699 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003700 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003701 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003702}
3703
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003704void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003705 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003706 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3707 if (mTorchClientMap[i] == who) {
3708 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003709 String8 cameraId = mTorchClientMap.keyAt(i);
3710 status_t res = mFlashlight->setTorchMode(cameraId, false);
3711 if (res) {
3712 ALOGE("%s: torch client died but couldn't turn off torch: "
3713 "%s (%d)", __FUNCTION__, strerror(-res), res);
3714 return;
3715 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003716 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003717 break;
3718 }
3719 }
3720}
3721
Ruben Brunkcc776712015-02-17 20:18:47 -08003722/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003723
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003724 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003725 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3726 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003727 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003728 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003729 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003730
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003731 // check torch client
3732 handleTorchClientBinderDied(who);
3733
3734 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003735 if(!evictClientIdByRemote(who)) {
3736 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003737 return;
3738 }
3739
Ruben Brunkcc776712015-02-17 20:18:47 -08003740 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3741 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003742}
3743
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003744void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003745 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003746}
3747
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003748void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3749 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003750 // Do not lock mServiceLock here or can get into a deadlock from
3751 // connect() -> disconnect -> updateStatus
3752
3753 auto state = getCameraState(cameraId);
3754
3755 if (state == nullptr) {
3756 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3757 cameraId.string());
3758 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003759 }
3760
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003761 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3762 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3763 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3764 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3765 return;
3766 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003767 bool supportsHAL3 = false;
3768 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3769 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3770 // mInterfaceMutex together, which can lead to deadlocks)
3771 binder::Status sRet =
3772 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3773 &supportsHAL3);
3774 if (!sRet.isOk()) {
3775 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3776 __FUNCTION__, cameraId.string());
3777 return;
3778 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003779
3780 // Collect the logical cameras without holding mStatusLock in updateStatus
3781 // as that can lead to a deadlock(b/162192331).
3782 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003783 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003784 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003785 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3786 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003787 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003788
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003789 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003790 // Update torch status if it has a flash unit.
3791 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003792 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003793 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3794 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003795 TorchModeStatus newTorchStatus =
3796 status == StatusInternal::PRESENT ?
3797 TorchModeStatus::AVAILABLE_OFF :
3798 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003799 if (torchStatus != newTorchStatus) {
Jayant Chowdharyaa6e3ea2021-03-31 02:13:46 -07003800 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003801 }
3802 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003803 }
3804
3805 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003806 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3807 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003808
Ruben Brunkcc776712015-02-17 20:18:47 -08003809 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003810 bool isVendorListener = listener->isVendorListener();
3811 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3812 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003813 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003814 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003815 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003816 continue;
3817 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003818 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003819 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003820 }
3821 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003822}
3823
Shuzhen Wang695044d2020-03-06 09:02:23 -08003824void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3825 const String16& clientPackageName) {
3826 Mutex::Autolock lock(mStatusListenerLock);
3827
3828 for (const auto& it : mListenerList) {
3829 if (!it->isOpenCloseCallbackAllowed()) {
3830 continue;
3831 }
3832
3833 binder::Status ret;
3834 String16 cameraId64(cameraId);
3835 if (open) {
3836 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3837 } else {
3838 ret = it->getListener()->onCameraClosed(cameraId64);
3839 }
3840 if (!ret.isOk()) {
3841 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3842 ret.exceptionCode());
3843 }
3844 }
3845}
3846
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003847template<class Func>
3848void CameraService::CameraState::updateStatus(StatusInternal status,
3849 const String8& cameraId,
3850 std::initializer_list<StatusInternal> rejectSourceStates,
3851 Func onStatusUpdatedLocked) {
3852 Mutex::Autolock lock(mStatusLock);
3853 StatusInternal oldStatus = mStatus;
3854 mStatus = status;
3855
3856 if (oldStatus == status) {
3857 return;
3858 }
3859
3860 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3861 cameraId.string(), oldStatus, status);
3862
3863 if (oldStatus == StatusInternal::NOT_PRESENT &&
3864 (status != StatusInternal::PRESENT &&
3865 status != StatusInternal::ENUMERATING)) {
3866
3867 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3868 __FUNCTION__);
3869 mStatus = oldStatus;
3870 return;
3871 }
3872
3873 /**
3874 * Sometimes we want to conditionally do a transition.
3875 * For example if a client disconnects, we want to go to PRESENT
3876 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3877 */
3878 for (auto& rejectStatus : rejectSourceStates) {
3879 if (oldStatus == rejectStatus) {
3880 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3881 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3882 mStatus = oldStatus;
3883 return;
3884 }
3885 }
3886
3887 onStatusUpdatedLocked(cameraId, status);
3888}
3889
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003890void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003891 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003892 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3893 if (proxyBinder == nullptr) return;
3894 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003895 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003896}
3897
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003898status_t CameraService::getTorchStatusLocked(
3899 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003900 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003901 if (!status) {
3902 return BAD_VALUE;
3903 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003904 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3905 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003906 // invalid camera ID or the camera doesn't have a flash unit
3907 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003908 }
3909
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003910 *status = mTorchStatusMap.valueAt(index);
3911 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003912}
3913
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003914status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003915 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003916 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3917 if (index == NAME_NOT_FOUND) {
3918 return BAD_VALUE;
3919 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003920 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003921
3922 return OK;
3923}
3924
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003925std::list<String16> CameraService::getLogicalCameras(
3926 const String8& physicalCameraId) {
3927 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003928 Mutex::Autolock lock(mCameraStatesLock);
3929 for (const auto& state : mCameraStates) {
3930 std::vector<std::string> physicalCameraIds;
3931 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3932 // This is not a logical multi-camera.
3933 continue;
3934 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003935 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003936 == physicalCameraIds.end()) {
3937 // cameraId is not a physical camera of this logical multi-camera.
3938 continue;
3939 }
3940
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003941 retList.emplace_back(String16(state.first));
3942 }
3943 return retList;
3944}
3945
3946void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3947 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3948 SystemCameraKind deviceKind) {
3949 // mStatusListenerLock is expected to be locked
3950 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003951 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003952 // Note: we check only the deviceKind of the physical camera id
3953 // since, logical camera ids and their physical camera ids are
3954 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003955 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3956 listener->getListenerPid(), listener->getListenerUid())) {
3957 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003958 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003959 continue;
3960 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003961 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003962 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003963 }
3964 }
3965}
3966
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003967
Svet Ganova453d0d2018-01-11 15:37:58 -08003968void CameraService::blockClientsForUid(uid_t uid) {
3969 const auto clients = mActiveClientManager.getAll();
3970 for (auto& current : clients) {
3971 if (current != nullptr) {
3972 const auto basicClient = current->getValue();
3973 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3974 basicClient->block();
3975 }
3976 }
3977 }
3978}
3979
Michael Grooverd1d435a2018-12-18 17:39:42 -08003980void CameraService::blockAllClients() {
3981 const auto clients = mActiveClientManager.getAll();
3982 for (auto& current : clients) {
3983 if (current != nullptr) {
3984 const auto basicClient = current->getValue();
3985 if (basicClient.get() != nullptr) {
3986 basicClient->block();
3987 }
3988 }
3989 }
3990}
3991
Svet Ganova453d0d2018-01-11 15:37:58 -08003992// NOTE: This is a remote API - make sure all args are validated
3993status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3994 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3995 return PERMISSION_DENIED;
3996 }
3997 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3998 return BAD_VALUE;
3999 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004000 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004001 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004002 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004003 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004004 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004005 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004006 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4007 return handleSetRotateAndCrop(args);
4008 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4009 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004010 } else if (args.size() == 1 && args[0] == String16("help")) {
4011 printHelp(out);
4012 return NO_ERROR;
4013 }
4014 printHelp(err);
4015 return BAD_VALUE;
4016}
4017
4018status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004019 String16 packageName = args[1];
4020
Svet Ganova453d0d2018-01-11 15:37:58 -08004021 bool active = false;
4022 if (args[2] == String16("active")) {
4023 active = true;
4024 } else if ((args[2] != String16("idle"))) {
4025 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4026 return BAD_VALUE;
4027 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004028
4029 int userId = 0;
4030 if (args.size() >= 5 && args[3] == String16("--user")) {
4031 userId = atoi(String8(args[4]));
4032 }
4033
4034 uid_t uid;
4035 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4036 return BAD_VALUE;
4037 }
4038
4039 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004040 return NO_ERROR;
4041}
4042
4043status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004044 String16 packageName = args[1];
4045
4046 int userId = 0;
4047 if (args.size() >= 4 && args[2] == String16("--user")) {
4048 userId = atoi(String8(args[3]));
4049 }
4050
4051 uid_t uid;
4052 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004053 return BAD_VALUE;
4054 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004055
4056 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004057 return NO_ERROR;
4058}
4059
4060status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004061 String16 packageName = args[1];
4062
4063 int userId = 0;
4064 if (args.size() >= 4 && args[2] == String16("--user")) {
4065 userId = atoi(String8(args[3]));
4066 }
4067
4068 uid_t uid;
4069 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004070 return BAD_VALUE;
4071 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004072
4073 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004074 return dprintf(out, "active\n");
4075 } else {
4076 return dprintf(out, "idle\n");
4077 }
4078}
4079
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004080status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4081 int rotateValue = atoi(String8(args[1]));
4082 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4083 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4084 Mutex::Autolock lock(mServiceLock);
4085
4086 mOverrideRotateAndCropMode = rotateValue;
4087
4088 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4089
4090 const auto clients = mActiveClientManager.getAll();
4091 for (auto& current : clients) {
4092 if (current != nullptr) {
4093 const auto basicClient = current->getValue();
4094 if (basicClient.get() != nullptr) {
4095 basicClient->setRotateAndCropOverride(rotateValue);
4096 }
4097 }
4098 }
4099
4100 return OK;
4101}
4102
4103status_t CameraService::handleGetRotateAndCrop(int out) {
4104 Mutex::Autolock lock(mServiceLock);
4105
4106 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4107}
4108
Svet Ganova453d0d2018-01-11 15:37:58 -08004109status_t CameraService::printHelp(int out) {
4110 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004111 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4112 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4113 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004114 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4115 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4116 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004117 " help print this message\n");
4118}
4119
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004120int32_t CameraService::updateAudioRestriction() {
4121 Mutex::Autolock lock(mServiceLock);
4122 return updateAudioRestrictionLocked();
4123}
4124
4125int32_t CameraService::updateAudioRestrictionLocked() {
4126 int32_t mode = 0;
4127 // iterate through all active client
4128 for (const auto& i : mActiveClientManager.getAll()) {
4129 const auto clientSp = i->getValue();
4130 mode |= clientSp->getAudioRestriction();
4131 }
4132
4133 bool modeChanged = (mAudioRestriction != mode);
4134 mAudioRestriction = mode;
4135 if (modeChanged) {
4136 mAppOps.setCameraAudioRestriction(mode);
4137 }
4138 return mode;
4139}
4140
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141}; // namespace android