blob: 721af95326775bb28c3c565f93e356fb5901691e [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>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080045#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000059#include <processinfo/ProcessInfoService.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 Chowdhary64d907a2021-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 Chowdhary64d907a2021-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 Chowdhary64d907a2021-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 Chowdhary64d907a2021-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 Chowdhary64d907a2021-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 Chowdhary64d907a2021-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 Chowdhary64d907a2021-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,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900817 const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800818 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),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900973 internalPackageName, {}, 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,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001491 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, {},
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001492 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,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001518 clientPackageName, {}, clientUid, USE_CALLING_PID, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001519 /*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,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001593 const std::optional<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,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001627 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001628 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 Chowdhary64d907a2021-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;
Dijack Dongc8a6f252021-09-17 16:21:16 +08001956 case -EBUSY:
1957 msg = String8::format("Camera \"%s\" is in use",
1958 id.string());
1959 errorCode = ERROR_CAMERA_IN_USE;
1960 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001961 default:
1962 msg = String8::format(
1963 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1964 id.string(), enabled, strerror(-err), err);
1965 errorCode = ERROR_INVALID_OPERATION;
1966 }
1967 ALOGE("%s: %s", __FUNCTION__, msg.string());
1968 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001969 }
1970
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001971 {
1972 // update the link to client's death
1973 Mutex::Autolock al(mTorchClientMapMutex);
1974 ssize_t index = mTorchClientMap.indexOfKey(id);
1975 if (enabled) {
1976 if (index == NAME_NOT_FOUND) {
1977 mTorchClientMap.add(id, clientBinder);
1978 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001979 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001980 mTorchClientMap.replaceValueAt(index, clientBinder);
1981 }
1982 clientBinder->linkToDeath(this);
1983 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001984 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001985 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001986 }
1987
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001988 int clientPid = CameraThreadState::getCallingPid();
1989 const char *id_cstr = id.c_str();
1990 const char *torchState = enabled ? "on" : "off";
1991 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1992 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001993 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001994}
1995
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001996Status CameraService::notifySystemEvent(int32_t eventId,
1997 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001998 const int pid = CameraThreadState::getCallingPid();
1999 const int selfPid = getpid();
2000
2001 // Permission checks
2002 if (pid != selfPid) {
2003 // Ensure we're being called by system_server, or similar process with
2004 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002005 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002006 const int uid = CameraThreadState::getCallingUid();
2007 ALOGE("Permission Denial: cannot send updates to camera service about system"
2008 " events from pid=%d, uid=%d", pid, uid);
2009 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002010 "No permission to send updates to camera service about system events"
2011 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002012 }
2013 }
2014
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002015 ATRACE_CALL();
2016
Ruben Brunk36597b22015-03-20 22:15:57 -07002017 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002018 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002019 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002020 // from a system server crash
2021 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002022 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002023 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002024 break;
2025 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002026 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002027 default: {
2028 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2029 eventId);
2030 break;
2031 }
2032 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002033 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002034}
2035
Emilian Peev53722fa2019-02-22 17:47:20 -08002036void CameraService::notifyMonitoredUids() {
2037 Mutex::Autolock lock(mStatusListenerLock);
2038
2039 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002040 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002041 if (!ret.isOk()) {
2042 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2043 ret.exceptionCode());
2044 }
2045 }
2046}
2047
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002048Status CameraService::notifyDeviceStateChange(int64_t newState) {
2049 const int pid = CameraThreadState::getCallingPid();
2050 const int selfPid = getpid();
2051
2052 // Permission checks
2053 if (pid != selfPid) {
2054 // Ensure we're being called by system_server, or similar process with
2055 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002056 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002057 const int uid = CameraThreadState::getCallingUid();
2058 ALOGE("Permission Denial: cannot send updates to camera service about device"
2059 " state changes from pid=%d, uid=%d", pid, uid);
2060 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2061 "No permission to send updates to camera service about device state"
2062 " changes from pid=%d, uid=%d", pid, uid);
2063 }
2064 }
2065
2066 ATRACE_CALL();
2067
2068 using hardware::camera::provider::V2_5::DeviceState;
2069 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2070 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2071 newDeviceState |= DeviceState::BACK_COVERED;
2072 }
2073 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2074 newDeviceState |= DeviceState::FRONT_COVERED;
2075 }
2076 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2077 newDeviceState |= DeviceState::FOLDED;
2078 }
2079 // Only map vendor bits directly
2080 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2081 newDeviceState |= vendorBits;
2082
2083 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2084 Mutex::Autolock l(mServiceLock);
2085 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2086
2087 return Status::ok();
2088}
2089
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002090 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002091 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2092 ATRACE_CALL();
2093 if (!concurrentCameraIds) {
2094 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2095 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2096 }
2097
2098 if (!mInitialized) {
2099 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2100 return STATUS_ERROR(ERROR_DISCONNECTED,
2101 "Camera subsystem is not available");
2102 }
2103 // First call into the provider and get the set of concurrent camera
2104 // combinations
2105 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002106 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002107 for (auto &combination : concurrentCameraCombinations) {
2108 std::vector<std::string> validCombination;
2109 for (auto &cameraId : combination) {
2110 // if the camera state is not present, skip
2111 String8 cameraIdStr(cameraId.c_str());
2112 auto state = getCameraState(cameraIdStr);
2113 if (state == nullptr) {
2114 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2115 continue;
2116 }
2117 StatusInternal status = state->getStatus();
2118 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2119 continue;
2120 }
2121 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2122 continue;
2123 }
2124 validCombination.push_back(cameraId);
2125 }
2126 if (validCombination.size() != 0) {
2127 concurrentCameraIds->push_back(std::move(validCombination));
2128 }
2129 }
2130 return Status::ok();
2131}
2132
2133Status CameraService::isConcurrentSessionConfigurationSupported(
2134 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2135 /*out*/bool* isSupported) {
2136 if (!isSupported) {
2137 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2138 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2139 }
2140
2141 if (!mInitialized) {
2142 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2143 return STATUS_ERROR(ERROR_DISCONNECTED,
2144 "Camera subsystem is not available");
2145 }
2146
2147 // Check for camera permissions
2148 int callingPid = CameraThreadState::getCallingPid();
2149 int callingUid = CameraThreadState::getCallingUid();
2150 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2151 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2152 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2153 "android.permission.CAMERA needed to call"
2154 "isConcurrentSessionConfigurationSupported");
2155 }
2156
2157 status_t res =
2158 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2159 cameraIdsAndSessionConfigurations, isSupported);
2160 if (res != OK) {
2161 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2162 "support %s (%d)", strerror(-res), res);
2163 }
2164 return Status::ok();
2165}
2166
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002167Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2168 /*out*/
2169 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002170 return addListenerHelper(listener, cameraStatuses);
2171}
2172
2173Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2174 /*out*/
2175 std::vector<hardware::CameraStatus> *cameraStatuses,
2176 bool isVendorListener) {
2177
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002178 ATRACE_CALL();
2179
Igor Murashkinbfc99152013-02-27 12:55:20 -08002180 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002181
Ruben Brunk3450ba72015-06-16 11:00:37 -07002182 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002183 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002184 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002185 }
2186
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002187 auto clientUid = CameraThreadState::getCallingUid();
2188 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002189 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2190 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002191
Igor Murashkinbfc99152013-02-27 12:55:20 -08002192 Mutex::Autolock lock(mServiceLock);
2193
Ruben Brunkcc776712015-02-17 20:18:47 -08002194 {
2195 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002196 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002197 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002198 ALOGW("%s: Tried to add listener %p which was already subscribed",
2199 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002200 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002201 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002202 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002203
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002204 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002205 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2206 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002207 auto ret = serviceListener->initialize();
2208 if (ret != NO_ERROR) {
2209 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2210 strerror(-ret), ret);
2211 ALOGE("%s: %s", __FUNCTION__, msg.string());
2212 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2213 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002214 // The listener still needs to be added to the list of listeners, regardless of what
2215 // permissions the listener process has / whether it is a vendor listener. Since it might be
2216 // eligible to listen to other camera ids.
2217 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002218 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002219 }
2220
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002221 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002222 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002223 Mutex::Autolock lock(mCameraStatesLock);
2224 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002225 cameraStatuses->emplace_back(i.first,
2226 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002227 }
2228 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002229 // Remove the camera statuses that should be hidden from the client, we do
2230 // this after collecting the states in order to avoid holding
2231 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2232 // the same time.
2233 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2234 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2235 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2236 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2237 ALOGE("%s: Invalid camera id %s, skipping status update",
2238 __FUNCTION__, s.cameraId.c_str());
2239 return true;
2240 }
2241 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2242 clientUid);}), cameraStatuses->end());
2243
Jayant Chowdhary64d907a2021-03-31 02:13:46 -07002244 //cameraStatuses will have non-eligible camera ids removed.
2245 std::set<String16> idsChosenForCallback;
2246 for (const auto &s : *cameraStatuses) {
2247 idsChosenForCallback.insert(String16(s.cameraId));
2248 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002249
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002250 /*
2251 * Immediately signal current torch status to this listener only
2252 * This may be a subset of all the devices, so don't include it in the response directly
2253 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002254 {
2255 Mutex::Autolock al(mTorchStatusMutex);
2256 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002257 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary64d907a2021-03-31 02:13:46 -07002258 // The camera id is visible to the client. Fine to send torch
2259 // callback.
2260 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2261 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2262 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002263 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002264 }
2265
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002267}
Ruben Brunkcc776712015-02-17 20:18:47 -08002268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002270 ATRACE_CALL();
2271
Igor Murashkinbfc99152013-02-27 12:55:20 -08002272 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2273
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002274 if (listener == 0) {
2275 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002276 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002277 }
2278
Igor Murashkinbfc99152013-02-27 12:55:20 -08002279 Mutex::Autolock lock(mServiceLock);
2280
Ruben Brunkcc776712015-02-17 20:18:47 -08002281 {
2282 Mutex::Autolock lock(mStatusListenerLock);
2283 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002284 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2285 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2286 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002287 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002288 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002289 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002290 }
2291 }
2292
2293 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2294 __FUNCTION__, listener.get());
2295
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002296 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002297}
2298
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002299Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002300
2301 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002302 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2303
2304 if (parameters == NULL) {
2305 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002307 }
2308
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002309 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002310
2311 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002313 // Error logged by caller
2314 return ret;
2315 }
2316
2317 String8 shimParamsString8 = shimParams.flatten();
2318 String16 shimParamsString16 = String16(shimParamsString8);
2319
2320 *parameters = shimParamsString16;
2321
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002322 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002323}
2324
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002325Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2326 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002327 ATRACE_CALL();
2328
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002329 const String8 id = String8(cameraId);
2330
2331 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002332
2333 switch (apiVersion) {
2334 case API_VERSION_1:
2335 case API_VERSION_2:
2336 break;
2337 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002338 String8 msg = String8::format("Unknown API version %d", apiVersion);
2339 ALOGE("%s: %s", __FUNCTION__, msg.string());
2340 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002341 }
2342
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002343 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002344 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002345 case CAMERA_DEVICE_API_VERSION_1_0:
2346 case CAMERA_DEVICE_API_VERSION_3_0:
2347 case CAMERA_DEVICE_API_VERSION_3_1:
2348 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002349 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2350 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002351 *isSupported = false;
2352 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002353 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2354 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002355 *isSupported = true;
2356 }
2357 break;
2358 case CAMERA_DEVICE_API_VERSION_3_2:
2359 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002360 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002361 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002362 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002363 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2364 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002365 *isSupported = true;
2366 break;
2367 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002368 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002369 ALOGE("%s: %s", __FUNCTION__, msg.string());
2370 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002371 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002372 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002373 String8 msg = String8::format("Unknown device version %x for device %s",
2374 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002375 ALOGE("%s: %s", __FUNCTION__, msg.string());
2376 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2377 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002378 }
2379
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002380 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002381}
2382
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002383Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2384 /*out*/ bool *isSupported) {
2385 ATRACE_CALL();
2386
2387 const String8 id = String8(cameraId);
2388
2389 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2390 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2391
2392 return Status::ok();
2393}
2394
Ruben Brunkcc776712015-02-17 20:18:47 -08002395void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002396 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002397 for (auto& i : mActiveClientManager.getAll()) {
2398 auto clientSp = i->getValue();
2399 if (clientSp.get() == client) {
2400 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002401 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002402 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002403 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002404}
2405
Ruben Brunkcc776712015-02-17 20:18:47 -08002406bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002407 bool ret = false;
2408 {
2409 // Acquire mServiceLock and prevent other clients from connecting
2410 std::unique_ptr<AutoConditionLock> lock =
2411 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002412
Igor Murashkin634a5152013-02-20 17:15:11 -08002413
Ruben Brunkcc776712015-02-17 20:18:47 -08002414 std::vector<sp<BasicClient>> evicted;
2415 for (auto& i : mActiveClientManager.getAll()) {
2416 auto clientSp = i->getValue();
2417 if (clientSp.get() == nullptr) {
2418 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2419 mActiveClientManager.remove(i);
2420 continue;
2421 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002422 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002423 mActiveClientManager.remove(i);
2424 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002425
Ruben Brunkcc776712015-02-17 20:18:47 -08002426 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002427 clientSp->notifyError(
2428 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002429 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002430 }
2431 }
2432
Ruben Brunkcc776712015-02-17 20:18:47 -08002433 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2434 // other clients from connecting in mServiceLockWrapper if held
2435 mServiceLock.unlock();
2436
Ruben Brunk36597b22015-03-20 22:15:57 -07002437 // Do not clear caller identity, remote caller should be client proccess
2438
Ruben Brunkcc776712015-02-17 20:18:47 -08002439 for (auto& i : evicted) {
2440 if (i.get() != nullptr) {
2441 i->disconnect();
2442 ret = true;
2443 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002444 }
2445
Ruben Brunkcc776712015-02-17 20:18:47 -08002446 // Reacquire mServiceLock
2447 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002448
Ruben Brunkcc776712015-02-17 20:18:47 -08002449 } // lock is destroyed, allow further connect calls
2450
2451 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002452}
2453
Ruben Brunkcc776712015-02-17 20:18:47 -08002454std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2455 const String8& cameraId) const {
2456 std::shared_ptr<CameraState> state;
2457 {
2458 Mutex::Autolock lock(mCameraStatesLock);
2459 auto iter = mCameraStates.find(cameraId);
2460 if (iter != mCameraStates.end()) {
2461 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 }
2463 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002464 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465}
2466
Ruben Brunkcc776712015-02-17 20:18:47 -08002467sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2468 // Remove from active clients list
2469 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2470 if (clientDescriptorPtr == nullptr) {
2471 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2472 cameraId.string());
2473 return sp<BasicClient>{nullptr};
2474 }
2475
2476 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002477}
2478
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002479void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002480 // Acquire mServiceLock and prevent other clients from connecting
2481 std::unique_ptr<AutoConditionLock> lock =
2482 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2483
Ruben Brunk6267b532015-04-30 17:44:07 -07002484 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002485 for (size_t i = 0; i < newUserIds.size(); i++) {
2486 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002487 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002488 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002489 return;
2490 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002491 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002492 }
2493
Ruben Brunka8ca9152015-04-07 14:23:40 -07002494
Ruben Brunk6267b532015-04-30 17:44:07 -07002495 if (newAllowedUsers == mAllowedUsers) {
2496 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2497 return;
2498 }
2499
2500 logUserSwitch(mAllowedUsers, newAllowedUsers);
2501
2502 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002503
2504 // Current user has switched, evict all current clients.
2505 std::vector<sp<BasicClient>> evicted;
2506 for (auto& i : mActiveClientManager.getAll()) {
2507 auto clientSp = i->getValue();
2508
2509 if (clientSp.get() == nullptr) {
2510 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2511 continue;
2512 }
2513
Ruben Brunk6267b532015-04-30 17:44:07 -07002514 // Don't evict clients that are still allowed.
2515 uid_t clientUid = clientSp->getClientUid();
2516 userid_t clientUserId = multiuser_get_user_id(clientUid);
2517 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2518 continue;
2519 }
2520
Ruben Brunk36597b22015-03-20 22:15:57 -07002521 evicted.push_back(clientSp);
2522
2523 String8 curTime = getFormattedCurrentTime();
2524
2525 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2526 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002527
Ruben Brunk36597b22015-03-20 22:15:57 -07002528 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002529 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002530 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2531 " to user switch.", i->getKey().string(),
2532 String8{clientSp->getPackageName()}.string(),
2533 i->getOwnerId(), i->getPriority().getScore(),
2534 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002535
2536 }
2537
2538 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2539 // blocking other clients from connecting in mServiceLockWrapper if held.
2540 mServiceLock.unlock();
2541
2542 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002543 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002544
2545 for (auto& i : evicted) {
2546 i->disconnect();
2547 }
2548
Jayant Chowdhary12361932018-08-27 14:46:13 -07002549 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002550
2551 // Reacquire mServiceLock
2552 mServiceLock.lock();
2553}
Ruben Brunkcc776712015-02-17 20:18:47 -08002554
Ruben Brunka8ca9152015-04-07 14:23:40 -07002555void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002556 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002557 Mutex::Autolock l(mLogLock);
2558 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559}
2560
Ruben Brunka8ca9152015-04-07 14:23:40 -07002561void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002562 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002563 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002564 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002565 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002566}
2567
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002568void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2569 const char* clientPackage) {
2570 // Log the clients evicted
2571 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2572 cameraId, clientPackage, clientPid));
2573}
2574
Ruben Brunka8ca9152015-04-07 14:23:40 -07002575void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002576 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002577 // Log the clients evicted
2578 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002579 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002580}
2581
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002582void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2583 const char* clientPackage) {
2584 // Log the clients evicted
2585 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2586 clientPackage, clientPid));
2587}
2588
Ruben Brunka8ca9152015-04-07 14:23:40 -07002589void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002590 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002591 // Log the client rejected
2592 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002593 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002594}
2595
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002596void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2597 // Log torch event
2598 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2599 torchState, clientPid));
2600}
2601
Ruben Brunk6267b532015-04-30 17:44:07 -07002602void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2603 const std::set<userid_t>& newUserIds) {
2604 String8 newUsers = toString(newUserIds);
2605 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002606 if (oldUsers.size() == 0) {
2607 oldUsers = "<None>";
2608 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002609 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002610 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002611 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002612}
2613
2614void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2615 // Log the device removal
2616 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2617}
2618
2619void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2620 // Log the device removal
2621 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2622}
2623
2624void CameraService::logClientDied(int clientPid, const char* reason) {
2625 // Log the device removal
2626 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002627}
2628
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002629void CameraService::logServiceError(const char* msg, int errorCode) {
2630 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002631 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002632}
2633
Ruben Brunk36597b22015-03-20 22:15:57 -07002634status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2635 uint32_t flags) {
2636
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 // Permission checks
2638 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002639 case SHELL_COMMAND_TRANSACTION: {
2640 int in = data.readFileDescriptor();
2641 int out = data.readFileDescriptor();
2642 int err = data.readFileDescriptor();
2643 int argc = data.readInt32();
2644 Vector<String16> args;
2645 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2646 args.add(data.readString16());
2647 }
2648 sp<IBinder> unusedCallback;
2649 sp<IResultReceiver> resultReceiver;
2650 status_t status;
2651 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2652 return status;
2653 }
2654 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2655 return status;
2656 }
2657 status = shellCommand(in, out, err, args);
2658 if (resultReceiver != nullptr) {
2659 resultReceiver->send(status);
2660 }
2661 return NO_ERROR;
2662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 }
2664
2665 return BnCameraService::onTransact(code, data, reply, flags);
2666}
2667
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668// We share the media players for shutter and recording sound for all clients.
2669// A reference count is kept to determine when we will actually release the
2670// media players.
2671
Jaekyun Seokef498052018-03-23 13:09:44 +09002672sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2673 sp<MediaPlayer> mp = new MediaPlayer();
2674 status_t error;
2675 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002676 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002677 error = mp->prepare();
2678 }
2679 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002680 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002681 mp->disconnect();
2682 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002683 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 }
2685 return mp;
2686}
2687
username5755fea2018-12-27 09:48:08 +08002688void CameraService::increaseSoundRef() {
2689 Mutex::Autolock lock(mSoundLock);
2690 mSoundRef++;
2691}
2692
2693void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002694 ATRACE_CALL();
2695
username5755fea2018-12-27 09:48:08 +08002696 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2697 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2698 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2699 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2700 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2701 }
2702 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2703 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2704 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2705 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002706 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002707 }
2708 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2709 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2710 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2711 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2712 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714}
2715
username5755fea2018-12-27 09:48:08 +08002716void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002718 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 if (--mSoundRef) return;
2720
2721 for (int i = 0; i < NUM_SOUNDS; i++) {
2722 if (mSoundPlayer[i] != 0) {
2723 mSoundPlayer[i]->disconnect();
2724 mSoundPlayer[i].clear();
2725 }
2726 }
2727}
2728
2729void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002730 ATRACE_CALL();
2731
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732 LOG1("playSound(%d)", kind);
2733 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002734 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735 sp<MediaPlayer> player = mSoundPlayer[kind];
2736 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002737 player->seekTo(0);
2738 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 }
2740}
2741
2742// ----------------------------------------------------------------------------
2743
2744CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002745 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002746 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002747 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002748 const String8& cameraIdStr,
2749 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002750 int clientPid, uid_t clientUid,
2751 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002752 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002753 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002754 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002755 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002756 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002757 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002758 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002759{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002760 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002761 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002763 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764
username5755fea2018-12-27 09:48:08 +08002765 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002766
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002767 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768}
2769
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770// tear down the client
2771CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002772 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002773 mDestructionStarted = true;
2774
username5755fea2018-12-27 09:48:08 +08002775 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002776 // unconditionally disconnect. function is idempotent
2777 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778}
2779
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002780sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2781
Igor Murashkin634a5152013-02-20 17:15:11 -08002782CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002783 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002784 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002785 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002786 int clientPid, uid_t clientUid,
2787 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002788 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002789 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002790 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002791 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002792 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002793 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002794 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002795{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002796 if (sCameraService == nullptr) {
2797 sCameraService = cameraService;
2798 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002799 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002800 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002801
2802 // In some cases the calling code has no access to the package it runs under.
2803 // For example, NDK camera API.
2804 // In this case we will get the packages for the calling UID and pick the first one
2805 // for attributing the app op. This will work correctly for runtime permissions
2806 // as for legacy apps we will toggle the app op for all packages in the UID.
2807 // The caveat is that the operation may be attributed to the wrong package and
2808 // stats based on app ops may be slightly off.
2809 if (mClientPackageName.size() <= 0) {
2810 sp<IServiceManager> sm = defaultServiceManager();
2811 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2812 if (binder == 0) {
2813 ALOGE("Cannot get permission service");
2814 // Leave mClientPackageName unchanged (empty) and the further interaction
2815 // with camera will fail in BasicClient::startCameraOps
2816 return;
2817 }
2818
2819 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2820 Vector<String16> packages;
2821
2822 permCtrl->getPackagesForUid(mClientUid, packages);
2823
2824 if (packages.isEmpty()) {
2825 ALOGE("No packages for calling UID");
2826 // Leave mClientPackageName unchanged (empty) and the further interaction
2827 // with camera will fail in BasicClient::startCameraOps
2828 return;
2829 }
2830 mClientPackageName = packages[0];
2831 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002832 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002833 mAppOpsManager = std::make_unique<AppOpsManager>();
2834 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002835
2836 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002837}
2838
2839CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002840 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002841 mDestructionStarted = true;
2842}
2843
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002844binder::Status CameraService::BasicClient::disconnect() {
2845 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002846 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002847 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002848 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002849 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002850
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002851 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002852 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002853 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2854 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002855
2856 sp<IBinder> remote = getRemote();
2857 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002858 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002859 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002860
2861 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002862 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002863 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2864 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2865 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002866
Igor Murashkincba2c162013-03-20 15:56:31 -07002867 // client shouldn't be able to call into us anymore
2868 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002869
2870 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002871}
2872
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002873status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2874 // No dumping of clients directly over Binder,
2875 // must go through CameraService::dump
2876 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002877 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002878 return OK;
2879}
2880
Ruben Brunkcc776712015-02-17 20:18:47 -08002881String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002882 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002883}
2884
2885
2886int CameraService::BasicClient::getClientPid() const {
2887 return mClientPid;
2888}
2889
Ruben Brunk6267b532015-04-30 17:44:07 -07002890uid_t CameraService::BasicClient::getClientUid() const {
2891 return mClientUid;
2892}
2893
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002894bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2895 // Defaults to API2.
2896 return level == API_2;
2897}
2898
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002899status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002900 {
2901 Mutex::Autolock l(mAudioRestrictionLock);
2902 mAudioRestriction = mode;
2903 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002904 sCameraService->updateAudioRestriction();
2905 return OK;
2906}
2907
2908int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002909 return sCameraService->updateAudioRestriction();
2910}
2911
2912int32_t CameraService::BasicClient::getAudioRestriction() const {
2913 Mutex::Autolock l(mAudioRestrictionLock);
2914 return mAudioRestriction;
2915}
2916
2917bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2918 switch (mode) {
2919 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2920 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2921 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2922 return true;
2923 default:
2924 return false;
2925 }
2926}
2927
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002928status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002929 ATRACE_CALL();
2930
Igor Murashkine6800ce2013-03-04 17:25:57 -08002931 {
2932 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002933 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002934 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002935 if (mAppOpsManager != nullptr) {
2936 // Notify app ops that the camera is not available
2937 mOpsCallback = new OpsCallback(this);
2938 int32_t res;
2939 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2940 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002941 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2942 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2943 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002944
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002945 if (res == AppOpsManager::MODE_ERRORED) {
2946 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2947 mCameraIdStr.string(), String8(mClientPackageName).string());
2948 return PERMISSION_DENIED;
2949 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002950
Shuzhen Wang2c656792020-04-13 17:36:49 -07002951 // If the calling Uid is trusted (a native service), the AppOpsManager could
2952 // return MODE_IGNORED. Do not treat such case as error.
2953 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002954 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2955 mCameraIdStr.string(), String8(mClientPackageName).string());
2956 // Return the same error as for device policy manager rejection
2957 return -EACCES;
2958 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002959 }
2960
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002961 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002962
2963 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002964 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002965
Emilian Peev573291c2018-02-10 02:10:56 +00002966 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2967 if (canCastToApiClient(API_2)) {
2968 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2969 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002970 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002971 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002972 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002973
Emilian Peev53722fa2019-02-22 17:47:20 -08002974 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2975
Shuzhen Wang695044d2020-03-06 09:02:23 -08002976 // Notify listeners of camera open/close status
2977 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2978
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002979 return OK;
2980}
2981
2982status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002983 ATRACE_CALL();
2984
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002985 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002986 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002987 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002988 if (mAppOpsManager != nullptr) {
2989 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002990 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002991 mOpsActive = false;
2992 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002993 // This function is called when a client disconnects. This should
2994 // release the camera, but actually only if it was in a proper
2995 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002996 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002997 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002998
Ruben Brunkcc776712015-02-17 20:18:47 -08002999 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003000 sCameraService->updateStatus(StatusInternal::PRESENT,
3001 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003002
Emilian Peev573291c2018-02-10 02:10:56 +00003003 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
3004 if (canCastToApiClient(API_2)) {
3005 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
3006 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003007 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003008 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00003009 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003010 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003011 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003012 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3013 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003014 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003015 mOpsCallback.clear();
3016
Emilian Peev53722fa2019-02-22 17:47:20 -08003017 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3018
Shuzhen Wang695044d2020-03-06 09:02:23 -08003019 // Notify listeners of camera open/close status
3020 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3021
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003022 return OK;
3023}
3024
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003025void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003026 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003027 if (mAppOpsManager == nullptr) {
3028 return;
3029 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003030 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003031 if (op != AppOpsManager::OP_CAMERA) {
3032 ALOGW("Unexpected app ops notification received: %d", op);
3033 return;
3034 }
3035
3036 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003037 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003038 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003039 ALOGV("checkOp returns: %d, %s ", res,
3040 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3041 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3042 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3043 "UNKNOWN");
3044
3045 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003046 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003047 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003048 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003049 }
3050}
3051
Svet Ganova453d0d2018-01-11 15:37:58 -08003052void CameraService::BasicClient::block() {
3053 ATRACE_CALL();
3054
3055 // Reset the client PID to allow server-initiated disconnect,
3056 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003057 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003058 CaptureResultExtras resultExtras; // a dummy result (invalid)
3059 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3060 disconnect();
3061}
3062
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063// ----------------------------------------------------------------------------
3064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003065void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003066 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003067 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003068 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003069 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3070 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3071 api1ErrorCode = CAMERA_ERROR_DISABLED;
3072 }
3073 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003074 } else {
3075 ALOGE("mRemoteCallback is NULL!!");
3076 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003077}
3078
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003079// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003081 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003082 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003083}
3084
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003085bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3086 return level == API_1;
3087}
3088
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003089CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3090 mClient(client) {
3091}
3092
3093void CameraService::Client::OpsCallback::opChanged(int32_t op,
3094 const String16& packageName) {
3095 sp<BasicClient> client = mClient.promote();
3096 if (client != NULL) {
3097 client->opChanged(op, packageName);
3098 }
3099}
3100
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003102// UidPolicy
3103// ----------------------------------------------------------------------------
3104
3105void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003106 Mutex::Autolock _l(mUidLock);
3107
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003108 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003109 status_t res = mAm.linkToDeath(this);
3110 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003111 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003112 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003113 ActivityManager::PROCESS_STATE_UNKNOWN,
3114 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003115 if (res == OK) {
3116 mRegistered = true;
3117 ALOGV("UidPolicy: Registered with ActivityManager");
3118 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003119}
3120
3121void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003122 Mutex::Autolock _l(mUidLock);
3123
Steven Moreland2f348142019-07-02 15:59:07 -07003124 mAm.unregisterUidObserver(this);
3125 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003126 mRegistered = false;
3127 mActiveUids.clear();
3128 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003129}
3130
3131void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3132 onUidIdle(uid, disabled);
3133}
3134
3135void CameraService::UidPolicy::onUidActive(uid_t uid) {
3136 Mutex::Autolock _l(mUidLock);
3137 mActiveUids.insert(uid);
3138}
3139
3140void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3141 bool deleted = false;
3142 {
3143 Mutex::Autolock _l(mUidLock);
3144 if (mActiveUids.erase(uid) > 0) {
3145 deleted = true;
3146 }
3147 }
3148 if (deleted) {
3149 sp<CameraService> service = mService.promote();
3150 if (service != nullptr) {
3151 service->blockClientsForUid(uid);
3152 }
3153 }
3154}
3155
Emilian Peev53722fa2019-02-22 17:47:20 -08003156void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003157 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003158 bool procStateChange = false;
3159 {
3160 Mutex::Autolock _l(mUidLock);
3161 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3162 (mMonitoredUids[uid].first != procState)) {
3163 mMonitoredUids[uid].first = procState;
3164 procStateChange = true;
3165 }
3166 }
3167
3168 if (procStateChange) {
3169 sp<CameraService> service = mService.promote();
3170 if (service != nullptr) {
3171 service->notifyMonitoredUids();
3172 }
3173 }
3174}
3175
3176void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3177 Mutex::Autolock _l(mUidLock);
3178 auto it = mMonitoredUids.find(uid);
3179 if (it != mMonitoredUids.end()) {
3180 it->second.second++;
3181 } else {
3182 mMonitoredUids.emplace(
3183 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3184 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3185 }
3186}
3187
3188void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3189 Mutex::Autolock _l(mUidLock);
3190 auto it = mMonitoredUids.find(uid);
3191 if (it != mMonitoredUids.end()) {
3192 it->second.second--;
3193 if (it->second.second == 0) {
3194 mMonitoredUids.erase(it);
3195 }
3196 } else {
3197 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3198 }
3199}
3200
Svet Ganov7b4ab782018-03-25 12:48:10 -07003201bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003202 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003203 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003204}
3205
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003206static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3207static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003208
Svet Ganov7b4ab782018-03-25 12:48:10 -07003209bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003210 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003211 // If activity manager is unreachable, assume everything is active
3212 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003213 return true;
3214 }
3215 auto it = mOverrideUids.find(uid);
3216 if (it != mOverrideUids.end()) {
3217 return it->second;
3218 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003219 bool active = mActiveUids.find(uid) != mActiveUids.end();
3220 if (!active) {
3221 // We want active UIDs to always access camera with their first attempt since
3222 // there is no guarantee the app is robustly written and would retry getting
3223 // the camera on failure. The inverse case is not a problem as we would take
3224 // camera away soon once we get the callback that the uid is no longer active.
3225 ActivityManager am;
3226 // Okay to access with a lock held as UID changes are dispatched without
3227 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003228 int64_t startTimeMillis = 0;
3229 do {
3230 // TODO: Fix this b/109950150!
3231 // Okay this is a hack. There is a race between the UID turning active and
3232 // activity being resumed. The proper fix is very risky, so we temporary add
3233 // some polling which should happen pretty rarely anyway as the race is hard
3234 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003235 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003236 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003237 if (active) {
3238 break;
3239 }
3240 if (startTimeMillis <= 0) {
3241 startTimeMillis = uptimeMillis();
3242 }
3243 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003244 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003245 if (remainingTimeMillis <= 0) {
3246 break;
3247 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003248 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3249
3250 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003251 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003252 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003253 } while (true);
3254
Svet Ganov7b4ab782018-03-25 12:48:10 -07003255 if (active) {
3256 // Now that we found out the UID is actually active, cache that
3257 mActiveUids.insert(uid);
3258 }
3259 }
3260 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003261}
3262
Varun Shahb42f1eb2019-04-16 14:45:13 -07003263int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3264 Mutex::Autolock _l(mUidLock);
3265 return getProcStateLocked(uid);
3266}
3267
3268int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3269 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3270 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3271 procState = mMonitoredUids[uid].first;
3272 }
3273 return procState;
3274}
3275
Svet Ganov7b4ab782018-03-25 12:48:10 -07003276void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3277 String16 callingPackage, bool active) {
3278 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003279}
3280
Svet Ganov7b4ab782018-03-25 12:48:10 -07003281void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3282 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003283}
3284
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003285void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3286 Mutex::Autolock _l(mUidLock);
3287 ALOGV("UidPolicy: ActivityManager has died");
3288 mRegistered = false;
3289 mActiveUids.clear();
3290}
3291
Svet Ganov7b4ab782018-03-25 12:48:10 -07003292void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3293 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003294 bool wasActive = false;
3295 bool isActive = false;
3296 {
3297 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003298 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003299 mOverrideUids.erase(uid);
3300 if (insert) {
3301 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3302 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003303 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003304 }
3305 if (wasActive != isActive && !isActive) {
3306 sp<CameraService> service = mService.promote();
3307 if (service != nullptr) {
3308 service->blockClientsForUid(uid);
3309 }
3310 }
3311}
3312
3313// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003314// SensorPrivacyPolicy
3315// ----------------------------------------------------------------------------
3316void CameraService::SensorPrivacyPolicy::registerSelf() {
3317 Mutex::Autolock _l(mSensorPrivacyLock);
3318 if (mRegistered) {
3319 return;
3320 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003321 mSpm.addSensorPrivacyListener(this);
3322 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3323 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003324 if (res == OK) {
3325 mRegistered = true;
3326 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3327 }
3328}
3329
3330void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3331 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003332 mSpm.removeSensorPrivacyListener(this);
3333 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003334 mRegistered = false;
3335 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3336}
3337
3338bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3339 Mutex::Autolock _l(mSensorPrivacyLock);
3340 return mSensorPrivacyEnabled;
3341}
3342
3343binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3344 {
3345 Mutex::Autolock _l(mSensorPrivacyLock);
3346 mSensorPrivacyEnabled = enabled;
3347 }
3348 // if sensor privacy is enabled then block all clients from accessing the camera
3349 if (enabled) {
3350 sp<CameraService> service = mService.promote();
3351 if (service != nullptr) {
3352 service->blockAllClients();
3353 }
3354 }
3355 return binder::Status::ok();
3356}
3357
3358void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3359 Mutex::Autolock _l(mSensorPrivacyLock);
3360 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3361 mRegistered = false;
3362}
3363
3364// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003365// CameraState
3366// ----------------------------------------------------------------------------
3367
3368CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003369 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3370 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3371 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003372
3373CameraService::CameraState::~CameraState() {}
3374
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003375CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003376 Mutex::Autolock lock(mStatusLock);
3377 return mStatus;
3378}
3379
Shuzhen Wang43858162020-01-10 13:42:15 -08003380std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3381 Mutex::Autolock lock(mStatusLock);
3382 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3383 return res;
3384}
3385
Ruben Brunkcc776712015-02-17 20:18:47 -08003386CameraParameters CameraService::CameraState::getShimParams() const {
3387 return mShimParams;
3388}
3389
3390void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3391 mShimParams = params;
3392}
3393
3394int CameraService::CameraState::getCost() const {
3395 return mCost;
3396}
3397
3398std::set<String8> CameraService::CameraState::getConflicting() const {
3399 return mConflicting;
3400}
3401
3402String8 CameraService::CameraState::getId() const {
3403 return mId;
3404}
3405
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003406SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3407 return mSystemCameraKind;
3408}
3409
Shuzhen Wang43858162020-01-10 13:42:15 -08003410bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3411 Mutex::Autolock lock(mStatusLock);
3412 auto result = mUnavailablePhysicalIds.insert(physicalId);
3413 return result.second;
3414}
3415
3416bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3417 Mutex::Autolock lock(mStatusLock);
3418 auto count = mUnavailablePhysicalIds.erase(physicalId);
3419 return count > 0;
3420}
3421
Ruben Brunkcc776712015-02-17 20:18:47 -08003422// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003423// ClientEventListener
3424// ----------------------------------------------------------------------------
3425
3426void CameraService::ClientEventListener::onClientAdded(
3427 const resource_policy::ClientDescriptor<String8,
3428 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003429 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003430 if (basicClient.get() != nullptr) {
3431 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3432 notifier.noteStartCamera(descriptor.getKey(),
3433 static_cast<int>(basicClient->getClientUid()));
3434 }
3435}
3436
3437void CameraService::ClientEventListener::onClientRemoved(
3438 const resource_policy::ClientDescriptor<String8,
3439 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003440 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003441 if (basicClient.get() != nullptr) {
3442 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3443 notifier.noteStopCamera(descriptor.getKey(),
3444 static_cast<int>(basicClient->getClientUid()));
3445 }
3446}
3447
3448
3449// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003450// CameraClientManager
3451// ----------------------------------------------------------------------------
3452
Ruben Brunk99e69712015-05-26 17:25:07 -07003453CameraService::CameraClientManager::CameraClientManager() {
3454 setListener(std::make_shared<ClientEventListener>());
3455}
3456
Ruben Brunkcc776712015-02-17 20:18:47 -08003457CameraService::CameraClientManager::~CameraClientManager() {}
3458
3459sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3460 const String8& id) const {
3461 auto descriptor = get(id);
3462 if (descriptor == nullptr) {
3463 return sp<BasicClient>{nullptr};
3464 }
3465 return descriptor->getValue();
3466}
3467
3468String8 CameraService::CameraClientManager::toString() const {
3469 auto all = getAll();
3470 String8 ret("[");
3471 bool hasAny = false;
3472 for (auto& i : all) {
3473 hasAny = true;
3474 String8 key = i->getKey();
3475 int32_t cost = i->getCost();
3476 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003477 int32_t score = i->getPriority().getScore();
3478 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003479 auto conflicting = i->getConflicting();
3480 auto clientSp = i->getValue();
3481 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003482 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003483 if (clientSp.get() != nullptr) {
3484 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003485 uid_t clientUid = clientSp->getClientUid();
3486 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003487 }
Emilian Peev8131a262017-02-01 12:33:43 +00003488 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3489 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003490
Ruben Brunk6267b532015-04-30 17:44:07 -07003491 if (clientSp.get() != nullptr) {
3492 ret.appendFormat("User Id: %d, ", clientUserId);
3493 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003494 if (packageName.size() != 0) {
3495 ret.appendFormat("Client Package Name: %s", packageName.string());
3496 }
3497
3498 ret.append(", Conflicting Client Devices: {");
3499 for (auto& j : conflicting) {
3500 ret.appendFormat("%s, ", j.string());
3501 }
3502 ret.append("})");
3503 }
3504 if (hasAny) ret.append("\n");
3505 ret.append("]\n");
3506 return ret;
3507}
3508
3509CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3510 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003511 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3512 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003513
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003514 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003515 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3516 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3517
Ruben Brunkcc776712015-02-17 20:18:47 -08003518 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003519 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003520}
3521
3522CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3523 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3524 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003525 partial->getConflicting(), partial->getPriority().getScore(),
3526 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003527}
3528
3529// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530
3531static const int kDumpLockRetries = 50;
3532static const int kDumpLockSleep = 60000;
3533
3534static bool tryLock(Mutex& mutex)
3535{
3536 bool locked = false;
3537 for (int i = 0; i < kDumpLockRetries; ++i) {
3538 if (mutex.tryLock() == NO_ERROR) {
3539 locked = true;
3540 break;
3541 }
3542 usleep(kDumpLockSleep);
3543 }
3544 return locked;
3545}
3546
3547status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003548 ATRACE_CALL();
3549
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003550 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003551 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003552 CameraThreadState::getCallingPid(),
3553 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003554 return NO_ERROR;
3555 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003556 bool locked = tryLock(mServiceLock);
3557 // failed to lock - CameraService is probably deadlocked
3558 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003559 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003560 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003561
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003562 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003563 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003564
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003565 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003566 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003567
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003568 if (locked) mServiceLock.unlock();
3569 return NO_ERROR;
3570 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003571 dprintf(fd, "\n== Service global info: ==\n\n");
3572 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003573 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003574 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3575 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003576 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3577 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3578 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003579 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003580 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3581 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003582
3583 dumpEventLog(fd);
3584
3585 bool stateLocked = tryLock(mCameraStatesLock);
3586 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003587 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003588 }
3589
Emilian Peevbd8c5032018-02-14 23:05:40 +00003590 int argSize = args.size();
3591 for (int i = 0; i < argSize; i++) {
3592 if (args[i] == TagMonitor::kMonitorOption) {
3593 if (i + 1 < argSize) {
3594 mMonitorTags = String8(args[i + 1]);
3595 }
3596 break;
3597 }
3598 }
3599
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003600 for (auto& state : mCameraStates) {
3601 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003602
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003603 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003604
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003605 CameraParameters p = state.second->getShimParams();
3606 if (!p.isEmpty()) {
3607 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3608 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003609 }
3610
3611 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003612 if (clientDescriptor != nullptr) {
3613 dprintf(fd, " Device %s is open. Client instance dump:\n",
3614 cameraId.string());
3615 dprintf(fd, " Client priority score: %d state: %d\n",
3616 clientDescriptor->getPriority().getScore(),
3617 clientDescriptor->getPriority().getState());
3618 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3619
3620 auto client = clientDescriptor->getValue();
3621 dprintf(fd, " Client package: %s\n",
3622 String8(client->getPackageName()).string());
3623
3624 client->dumpClient(fd, args);
3625 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003626 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003627 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003628 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003629
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003630 }
3631
3632 if (stateLocked) mCameraStatesLock.unlock();
3633
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003634 if (locked) mServiceLock.unlock();
3635
Emilian Peevf53f66e2017-04-11 14:29:43 +01003636 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003637
3638 dprintf(fd, "\n== Vendor tags: ==\n\n");
3639
3640 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3641 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003642 sp<VendorTagDescriptorCache> cache =
3643 VendorTagDescriptorCache::getGlobalVendorTagCache();
3644 if (cache == NULL) {
3645 dprintf(fd, "No vendor tags.\n");
3646 } else {
3647 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3648 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003649 } else {
3650 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3651 }
3652
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003653 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003654 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003655 camera3::CameraTraces::dump(fd, args);
3656
3657 // Process dump arguments, if any
3658 int n = args.size();
3659 String16 verboseOption("-v");
3660 String16 unreachableOption("--unreachable");
3661 for (int i = 0; i < n; i++) {
3662 if (args[i] == verboseOption) {
3663 // change logging level
3664 if (i + 1 >= n) continue;
3665 String8 levelStr(args[i+1]);
3666 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003667 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003668 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003669 } else if (args[i] == unreachableOption) {
3670 // Dump memory analysis
3671 // TODO - should limit be an argument parameter?
3672 UnreachableMemoryInfo info;
3673 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3674 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003675 dprintf(fd, "\n== Unable to dump unreachable memory. "
3676 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003677 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003678 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003679 std::string s = info.ToString(/*log_contents*/ true);
3680 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681 }
3682 }
3683 }
3684 return NO_ERROR;
3685}
3686
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003687void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003688 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003689
3690 Mutex::Autolock l(mLogLock);
3691 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003692 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003693 }
3694
3695 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003696 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003697 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003698 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003699 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003700 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003701}
3702
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003703void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003704 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003705 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3706 if (mTorchClientMap[i] == who) {
3707 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003708 String8 cameraId = mTorchClientMap.keyAt(i);
3709 status_t res = mFlashlight->setTorchMode(cameraId, false);
3710 if (res) {
3711 ALOGE("%s: torch client died but couldn't turn off torch: "
3712 "%s (%d)", __FUNCTION__, strerror(-res), res);
3713 return;
3714 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003715 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003716 break;
3717 }
3718 }
3719}
3720
Ruben Brunkcc776712015-02-17 20:18:47 -08003721/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003722
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003723 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003724 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3725 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003726 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003727 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003728 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003729
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003730 // check torch client
3731 handleTorchClientBinderDied(who);
3732
3733 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003734 if(!evictClientIdByRemote(who)) {
3735 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003736 return;
3737 }
3738
Ruben Brunkcc776712015-02-17 20:18:47 -08003739 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3740 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003741}
3742
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003743void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003744 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003745}
3746
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003747void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3748 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003749 // Do not lock mServiceLock here or can get into a deadlock from
3750 // connect() -> disconnect -> updateStatus
3751
3752 auto state = getCameraState(cameraId);
3753
3754 if (state == nullptr) {
3755 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3756 cameraId.string());
3757 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003758 }
3759
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003760 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3761 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3762 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3763 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3764 return;
3765 }
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003766
3767 // Collect the logical cameras without holding mStatusLock in updateStatus
3768 // as that can lead to a deadlock(b/162192331).
3769 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003770 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003771 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wang7e53dc32021-05-27 09:27:06 -07003772 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003773 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003774 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003775
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003776 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003777 // Update torch status if it has a flash unit.
3778 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003779 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003780 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3781 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003782 TorchModeStatus newTorchStatus =
3783 status == StatusInternal::PRESENT ?
3784 TorchModeStatus::AVAILABLE_OFF :
3785 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003786 if (torchStatus != newTorchStatus) {
Jayant Chowdhary64d907a2021-03-31 02:13:46 -07003787 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003788 }
3789 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003790 }
3791
3792 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003793 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3794 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003795
Ruben Brunkcc776712015-02-17 20:18:47 -08003796 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003797 bool isVendorListener = listener->isVendorListener();
3798 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3799 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wang7e53dc32021-05-27 09:27:06 -07003800 isVendorListener) {
3801 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003802 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003803 continue;
3804 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003805 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003806 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003807 }
3808 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003809}
3810
Shuzhen Wang695044d2020-03-06 09:02:23 -08003811void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3812 const String16& clientPackageName) {
3813 Mutex::Autolock lock(mStatusListenerLock);
3814
3815 for (const auto& it : mListenerList) {
3816 if (!it->isOpenCloseCallbackAllowed()) {
3817 continue;
3818 }
3819
3820 binder::Status ret;
3821 String16 cameraId64(cameraId);
3822 if (open) {
3823 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3824 } else {
3825 ret = it->getListener()->onCameraClosed(cameraId64);
3826 }
3827 if (!ret.isOk()) {
3828 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3829 ret.exceptionCode());
3830 }
3831 }
3832}
3833
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003834template<class Func>
3835void CameraService::CameraState::updateStatus(StatusInternal status,
3836 const String8& cameraId,
3837 std::initializer_list<StatusInternal> rejectSourceStates,
3838 Func onStatusUpdatedLocked) {
3839 Mutex::Autolock lock(mStatusLock);
3840 StatusInternal oldStatus = mStatus;
3841 mStatus = status;
3842
3843 if (oldStatus == status) {
3844 return;
3845 }
3846
3847 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3848 cameraId.string(), oldStatus, status);
3849
3850 if (oldStatus == StatusInternal::NOT_PRESENT &&
3851 (status != StatusInternal::PRESENT &&
3852 status != StatusInternal::ENUMERATING)) {
3853
3854 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3855 __FUNCTION__);
3856 mStatus = oldStatus;
3857 return;
3858 }
3859
3860 /**
3861 * Sometimes we want to conditionally do a transition.
3862 * For example if a client disconnects, we want to go to PRESENT
3863 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3864 */
3865 for (auto& rejectStatus : rejectSourceStates) {
3866 if (oldStatus == rejectStatus) {
3867 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3868 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3869 mStatus = oldStatus;
3870 return;
3871 }
3872 }
3873
3874 onStatusUpdatedLocked(cameraId, status);
3875}
3876
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003877void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003878 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003879 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3880 if (proxyBinder == nullptr) return;
3881 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003882 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003883}
3884
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003885status_t CameraService::getTorchStatusLocked(
3886 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003887 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003888 if (!status) {
3889 return BAD_VALUE;
3890 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003891 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3892 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003893 // invalid camera ID or the camera doesn't have a flash unit
3894 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003895 }
3896
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003897 *status = mTorchStatusMap.valueAt(index);
3898 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003899}
3900
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003901status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003902 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003903 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3904 if (index == NAME_NOT_FOUND) {
3905 return BAD_VALUE;
3906 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003907 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003908
3909 return OK;
3910}
3911
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003912std::list<String16> CameraService::getLogicalCameras(
3913 const String8& physicalCameraId) {
3914 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003915 Mutex::Autolock lock(mCameraStatesLock);
3916 for (const auto& state : mCameraStates) {
3917 std::vector<std::string> physicalCameraIds;
3918 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3919 // This is not a logical multi-camera.
3920 continue;
3921 }
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003922 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003923 == physicalCameraIds.end()) {
3924 // cameraId is not a physical camera of this logical multi-camera.
3925 continue;
3926 }
3927
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003928 retList.emplace_back(String16(state.first));
3929 }
3930 return retList;
3931}
3932
3933void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3934 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3935 SystemCameraKind deviceKind) {
3936 // mStatusListenerLock is expected to be locked
3937 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003938 for (auto& listener : mListenerList) {
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003939 // Note: we check only the deviceKind of the physical camera id
3940 // since, logical camera ids and their physical camera ids are
3941 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003942 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3943 listener->getListenerPid(), listener->getListenerUid())) {
3944 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003945 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003946 continue;
3947 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003948 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003949 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003950 }
3951 }
3952}
3953
Jayant Chowdhary1e9ef4c2020-08-14 02:48:34 +00003954
Svet Ganova453d0d2018-01-11 15:37:58 -08003955void CameraService::blockClientsForUid(uid_t uid) {
3956 const auto clients = mActiveClientManager.getAll();
3957 for (auto& current : clients) {
3958 if (current != nullptr) {
3959 const auto basicClient = current->getValue();
3960 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3961 basicClient->block();
3962 }
3963 }
3964 }
3965}
3966
Michael Grooverd1d435a2018-12-18 17:39:42 -08003967void CameraService::blockAllClients() {
3968 const auto clients = mActiveClientManager.getAll();
3969 for (auto& current : clients) {
3970 if (current != nullptr) {
3971 const auto basicClient = current->getValue();
3972 if (basicClient.get() != nullptr) {
3973 basicClient->block();
3974 }
3975 }
3976 }
3977}
3978
Svet Ganova453d0d2018-01-11 15:37:58 -08003979// NOTE: This is a remote API - make sure all args are validated
3980status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3981 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3982 return PERMISSION_DENIED;
3983 }
3984 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3985 return BAD_VALUE;
3986 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003987 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003988 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003989 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003990 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003991 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003992 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003993 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3994 return handleSetRotateAndCrop(args);
3995 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3996 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003997 } else if (args.size() == 1 && args[0] == String16("help")) {
3998 printHelp(out);
3999 return NO_ERROR;
4000 }
4001 printHelp(err);
4002 return BAD_VALUE;
4003}
4004
4005status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004006 String16 packageName = args[1];
4007
Svet Ganova453d0d2018-01-11 15:37:58 -08004008 bool active = false;
4009 if (args[2] == String16("active")) {
4010 active = true;
4011 } else if ((args[2] != String16("idle"))) {
4012 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4013 return BAD_VALUE;
4014 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004015
4016 int userId = 0;
4017 if (args.size() >= 5 && args[3] == String16("--user")) {
4018 userId = atoi(String8(args[4]));
4019 }
4020
4021 uid_t uid;
4022 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4023 return BAD_VALUE;
4024 }
4025
4026 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004027 return NO_ERROR;
4028}
4029
4030status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004031 String16 packageName = args[1];
4032
4033 int userId = 0;
4034 if (args.size() >= 4 && args[2] == String16("--user")) {
4035 userId = atoi(String8(args[3]));
4036 }
4037
4038 uid_t uid;
4039 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004040 return BAD_VALUE;
4041 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004042
4043 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004044 return NO_ERROR;
4045}
4046
4047status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004048 String16 packageName = args[1];
4049
4050 int userId = 0;
4051 if (args.size() >= 4 && args[2] == String16("--user")) {
4052 userId = atoi(String8(args[3]));
4053 }
4054
4055 uid_t uid;
4056 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004057 return BAD_VALUE;
4058 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004059
4060 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004061 return dprintf(out, "active\n");
4062 } else {
4063 return dprintf(out, "idle\n");
4064 }
4065}
4066
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004067status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4068 int rotateValue = atoi(String8(args[1]));
4069 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4070 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4071 Mutex::Autolock lock(mServiceLock);
4072
4073 mOverrideRotateAndCropMode = rotateValue;
4074
4075 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4076
4077 const auto clients = mActiveClientManager.getAll();
4078 for (auto& current : clients) {
4079 if (current != nullptr) {
4080 const auto basicClient = current->getValue();
4081 if (basicClient.get() != nullptr) {
4082 basicClient->setRotateAndCropOverride(rotateValue);
4083 }
4084 }
4085 }
4086
4087 return OK;
4088}
4089
4090status_t CameraService::handleGetRotateAndCrop(int out) {
4091 Mutex::Autolock lock(mServiceLock);
4092
4093 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4094}
4095
Svet Ganova453d0d2018-01-11 15:37:58 -08004096status_t CameraService::printHelp(int out) {
4097 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004098 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4099 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4100 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004101 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4102 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4103 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004104 " help print this message\n");
4105}
4106
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004107int32_t CameraService::updateAudioRestriction() {
4108 Mutex::Autolock lock(mServiceLock);
4109 return updateAudioRestrictionLocked();
4110}
4111
4112int32_t CameraService::updateAudioRestrictionLocked() {
4113 int32_t mode = 0;
4114 // iterate through all active client
4115 for (const auto& i : mActiveClientManager.getAll()) {
4116 const auto clientSp = i->getValue();
4117 mode |= clientSp->getAudioRestriction();
4118 }
4119
4120 bool modeChanged = (mAudioRestriction != mode);
4121 mAudioRestriction = mode;
4122 if (modeChanged) {
4123 mAppOps.setCameraAudioRestriction(mode);
4124 }
4125 return mode;
4126}
4127
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128}; // namespace android