blob: 8400dae1c0faa8128844133e80353d331fdefb86 [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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/MemoryBase.h>
41#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080043#include <binder/ProcessInfoService.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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <utils/Errors.h>
60#include <utils/Log.h>
61#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070062#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080063#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080064#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080065#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080066#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070067#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080068
Ruben Brunkb2119af2014-05-09 19:57:56 -070069#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070072#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070074#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000075#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070076#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070077#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080079namespace {
80 const char* kPermissionServiceName = "permission";
81}; // namespace anonymous
82
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070085using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080086using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070087using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080088using hardware::ICamera;
89using hardware::ICameraClient;
90using hardware::ICameraServiceListener;
91using hardware::camera::common::V1_0::CameraDeviceStatus;
92using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080093using hardware::camera2::utils::CameraIdAndSessionConfiguration;
94using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080095
Mathias Agopian65ab4712010-07-14 17:59:35 -070096// ----------------------------------------------------------------------------
97// Logging support -- this is for debugging only
98// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070099volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100
Steve Blockb8a80522011-12-20 16:23:08 +0000101#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
102#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103
104static void setLogLevel(int level) {
105 android_atomic_write(level, &gLogLevel);
106}
107
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800108// Convenience methods for constructing binder::Status objects for error returns
109
110#define STATUS_ERROR(errorCode, errorString) \
111 binder::Status::fromServiceSpecificError(errorCode, \
112 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
113
114#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
115 binder::Status::fromServiceSpecificError(errorCode, \
116 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
117 __VA_ARGS__))
118
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119// ----------------------------------------------------------------------------
120
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700121static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800122static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700123static const String16 sCameraPermission("android.permission.CAMERA");
124static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
125static const String16
126 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800127static const String16 sCameraOpenCloseListenerPermission(
128 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800129
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700130// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
131static constexpr int32_t kVendorClientScore = 200;
132// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
133static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800134const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700135
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800136CameraService::CameraService() :
137 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800138 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700139 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700140 mSoundRef(0), mInitialized(false),
141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000142 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800143 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144}
145
Iliyan Malchev8951a972011-04-14 16:55:59 -0700146void CameraService::onFirstRef()
147{
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800149
Iliyan Malchev8951a972011-04-14 16:55:59 -0700150 BnCameraService::onFirstRef();
151
Ruben Brunk99e69712015-05-26 17:25:07 -0700152 // Update battery life tracking if service is restarting
153 BatteryNotifier& notifier(BatteryNotifier::getInstance());
154 notifier.noteResetCamera();
155 notifier.noteResetFlashlight();
156
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800157 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800158
Emilian Peevf53f66e2017-04-11 14:29:43 +0100159 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800160 if (res == OK) {
161 mInitialized = true;
162 }
163
Svet Ganova453d0d2018-01-11 15:37:58 -0800164 mUidPolicy = new UidPolicy(this);
165 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800166 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
167 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700168 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700169 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
170 if (hcs->registerAsService() != android::OK) {
171 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
172 __FUNCTION__);
173 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700174
175 // This needs to be last call in this function, so that it's as close to
176 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700177 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700178 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800179}
180
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800181status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100183
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800184 std::vector<std::string> deviceIds;
185 {
186 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800188 if (nullptr == mCameraProviderManager.get()) {
189 mCameraProviderManager = new CameraProviderManager();
190 res = mCameraProviderManager->initialize(this);
191 if (res != OK) {
192 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
193 __FUNCTION__, strerror(-res), res);
194 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100195 }
196 }
197
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800198
199 // Setup vendor tags before we call get_camera_info the first time
200 // because HAL might need to setup static vendor keys in get_camera_info
201 // TODO: maybe put this into CameraProviderManager::initialize()?
202 mCameraProviderManager->setUpVendorTags();
203
204 if (nullptr == mFlashlight.get()) {
205 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700206 }
207
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800208 res = mFlashlight->findFlashUnits();
209 if (res != OK) {
210 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
211 }
212
213 deviceIds = mCameraProviderManager->getCameraDeviceIds();
214 }
215
216
217 for (auto& cameraId : deviceIds) {
218 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800219 if (getCameraState(id8) == nullptr) {
220 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
221 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800222 }
223
224 return OK;
225}
226
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800227void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
228 Mutex::Autolock lock(mStatusListenerLock);
229
230 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700231 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800232 }
233}
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800236 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800237 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800238 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239}
240
Emilian Peevaee727d2017-05-04 16:35:48 +0100241void CameraService::onNewProviderRegistered() {
242 enumerateProviders();
243}
244
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700245void CameraService::filterAPI1SystemCameraLocked(
246 const std::vector<std::string> &normalDeviceIds) {
247 mNormalDeviceIdsWithoutSystemCamera.clear();
248 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700249 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
250 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
251 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
252 continue;
253 }
254 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700255 // All system camera ids will necessarily come after public camera
256 // device ids as per the HAL interface contract.
257 break;
258 }
259 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
260 }
261 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
262 mNormalDeviceIdsWithoutSystemCamera.size());
263}
264
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700265status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
266 auto state = getCameraState(cameraId);
267 if (state != nullptr) {
268 *kind = state->getSystemCameraKind();
269 return OK;
270 }
271 // Hidden physical camera ids won't have CameraState
272 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
273}
274
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800275void CameraService::updateCameraNumAndIds() {
276 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700277 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
278 // Excludes hidden secure cameras
279 mNumberOfCameras =
280 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
281 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 mNormalDeviceIds =
283 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700284 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800285}
286
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100287void CameraService::addStates(const String8 id) {
288 std::string cameraId(id.c_str());
289 hardware::camera::common::V1_0::CameraResourceCost cost;
290 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700291 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100292 if (res != OK) {
293 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
294 return;
295 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700296 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
297 if (res != OK) {
298 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
299 return;
300 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100301 std::set<String8> conflicting;
302 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
303 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
304 }
305
306 {
307 Mutex::Autolock lock(mCameraStatesLock);
308 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700309 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100310 }
311
312 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100313 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100314 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800315
316 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100317 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800318
319 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100320 logDeviceAdded(id, "Device added");
321}
322
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100323void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800324 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100325 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100326 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100327 mTorchStatusMap.removeItem(id);
328 }
329
330 {
331 Mutex::Autolock lock(mCameraStatesLock);
332 mCameraStates.erase(id);
333 }
334}
335
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800336void CameraService::onDeviceStatusChanged(const String8& id,
337 CameraDeviceStatus newHalStatus) {
338 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
339 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700340
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800341 StatusInternal newStatus = mapToInternal(newHalStatus);
342
Ruben Brunkcc776712015-02-17 20:18:47 -0800343 std::shared_ptr<CameraState> state = getCameraState(id);
344
345 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700346 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100347 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700348 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100349
350 // First add as absent to make sure clients are notified below
351 addStates(id);
352
353 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700354 } else {
355 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
356 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700357 return;
358 }
359
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800360 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800361
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800362 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800363 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700364 return;
365 }
366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800367 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700368 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
369 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800370
371 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
372 // to this device until the status changes
373 updateStatus(StatusInternal::NOT_PRESENT, id);
374
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800375 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700376 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800377 // Don't do this in updateStatus to avoid deadlock over mServiceLock
378 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700379
Ruben Brunkcc776712015-02-17 20:18:47 -0800380 // Remove cached shim parameters
381 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700382
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800383 // Remove online as well as offline client from the list of active clients,
384 // if they are present
385 clientToDisconnectOnline = removeClientLocked(id);
386 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700387 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800388
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800389 disconnectClient(id, clientToDisconnectOnline);
390 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700391
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100392 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800393 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800394 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700395 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
396 newStatus));
397 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800398 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700399 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800400}
Igor Murashkincba2c162013-03-20 15:56:31 -0700401
Shuzhen Wang43858162020-01-10 13:42:15 -0800402void CameraService::onDeviceStatusChanged(const String8& id,
403 const String8& physicalId,
404 CameraDeviceStatus newHalStatus) {
405 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
406 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
407
408 StatusInternal newStatus = mapToInternal(newHalStatus);
409
410 std::shared_ptr<CameraState> state = getCameraState(id);
411
412 if (state == nullptr) {
413 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
414 __FUNCTION__, id.string(), physicalId.string());
415 return;
416 }
417
418 StatusInternal logicalCameraStatus = state->getStatus();
419 if (logicalCameraStatus != StatusInternal::PRESENT &&
420 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
421 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
422 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
423 return;
424 }
425
426 bool updated = false;
427 if (newStatus == StatusInternal::PRESENT) {
428 updated = state->removeUnavailablePhysicalId(physicalId);
429 } else {
430 updated = state->addUnavailablePhysicalId(physicalId);
431 }
432
433 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800434 String8 idCombo = id + " : " + physicalId;
435 if (newStatus == StatusInternal::PRESENT) {
436 logDeviceAdded(idCombo,
437 String8::format("Device status changed to %d", newStatus));
438 } else {
439 logDeviceRemoved(idCombo,
440 String8::format("Device status changed to %d", newStatus));
441 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700442 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
443 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
444 if (getSystemCameraKind(id, &deviceKind) != OK) {
445 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
446 return;
447 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800448 String16 id16(id), physicalId16(physicalId);
449 Mutex::Autolock lock(mStatusListenerLock);
450 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700451 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
452 listener->getListenerPid(), listener->getListenerUid())) {
453 ALOGV("Skipping discovery callback for system-only camera device %s",
454 id.c_str());
455 continue;
456 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800457 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
458 id16, physicalId16);
459 }
460 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700461}
462
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800463void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
464 if (clientToDisconnect.get() != nullptr) {
465 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
466 __FUNCTION__, id.string());
467 // Notify the client of disconnection
468 clientToDisconnect->notifyError(
469 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
470 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800471 clientToDisconnect->disconnect();
472 }
473}
474
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800475void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800476 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800477 Mutex::Autolock al(mTorchStatusMutex);
478 onTorchStatusChangedLocked(cameraId, newStatus);
479}
480
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800481void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800482 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800483 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
484 __FUNCTION__, cameraId.string(), newStatus);
485
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800486 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800487 status_t res = getTorchStatusLocked(cameraId, &status);
488 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700489 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
490 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800491 return;
492 }
493 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800494 return;
495 }
496
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800497 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800498 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800499 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
500 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800501 return;
502 }
503
Ruben Brunkcc776712015-02-17 20:18:47 -0800504 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700505 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700506 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700507 auto iter = mTorchUidMap.find(cameraId);
508 if (iter != mTorchUidMap.end()) {
509 int oldUid = iter->second.second;
510 int newUid = iter->second.first;
511 BatteryNotifier& notifier(BatteryNotifier::getInstance());
512 if (oldUid != newUid) {
513 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700515 notifier.noteFlashlightOff(cameraId, oldUid);
516 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700518 notifier.noteFlashlightOn(cameraId, newUid);
519 }
520 iter->second.second = newUid;
521 } else {
522 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800523 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700524 notifier.noteFlashlightOn(cameraId, oldUid);
525 } else {
526 notifier.noteFlashlightOff(cameraId, oldUid);
527 }
528 }
529 }
530 }
531
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800532 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800533}
534
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700535static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
536 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
537 checkPermission(sCameraPermission, callingPid, callingUid);
538}
539
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800540Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700541 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100542 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700543 bool hasSystemCameraPermissions =
544 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
545 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700546 switch (type) {
547 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700548 if (hasSystemCameraPermissions) {
549 *numCameras = static_cast<int>(mNormalDeviceIds.size());
550 } else {
551 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
552 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800553 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700554 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700555 if (hasSystemCameraPermissions) {
556 *numCameras = mNumberOfCameras;
557 } else {
558 *numCameras = mNumberOfCamerasWithoutSystemCamera;
559 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800560 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700561 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800562 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700563 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800564 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
565 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700566 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800567 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568}
569
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800570Status CameraService::getCameraInfo(int cameraId,
571 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700572 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100573 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700574 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
575 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
576 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
577 "characteristics for system only device %s: ", cameraIdStr.c_str());
578 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100579
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800580 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800581 return STATUS_ERROR(ERROR_DISCONNECTED,
582 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700583 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700584 bool hasSystemCameraPermissions =
585 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
586 CameraThreadState::getCallingUid());
587 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
588 if (hasSystemCameraPermissions) {
589 cameraIdBound = mNumberOfCameras;
590 }
591 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800592 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
593 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 }
595
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800596 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800597 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700598 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100599 if (err != OK) {
600 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
601 "Error retrieving camera info from device %d: %s (%d)", cameraId,
602 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800603 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100604
Ruben Brunkcc776712015-02-17 20:18:47 -0800605 return ret;
606}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700607
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800608std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700609 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
610 auto callingPid = CameraThreadState::getCallingPid();
611 auto callingUid = CameraThreadState::getCallingUid();
612 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
613 getpid() == callingPid) {
614 deviceIds = &mNormalDeviceIds;
615 }
616 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800617 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700618 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800619 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800620 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800621
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700622 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800623}
624
625String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
626 Mutex::Autolock lock(mServiceLock);
627 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800628}
629
630Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800631 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700632 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700633 if (!cameraInfo) {
634 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800635 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700636 }
637
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800638 if (!mInitialized) {
639 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800640 return STATUS_ERROR(ERROR_DISCONNECTED,
641 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700642 }
643
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700644 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
645 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
646 "characteristics for system only device %s: ", String8(cameraId).string());
647 }
648
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800649 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800650
Emilian Peevf53f66e2017-04-11 14:29:43 +0100651 status_t res = mCameraProviderManager->getCameraCharacteristics(
652 String8(cameraId).string(), cameraInfo);
653 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700654 if (res == NAME_NOT_FOUND) {
655 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
656 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
657 strerror(-res), res);
658 } else {
659 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
660 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
661 strerror(-res), res);
662 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700663 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700664 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
665 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
666 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
667 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
668 "for device %s", String8(cameraId).string());
669 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700670 int callingPid = CameraThreadState::getCallingPid();
671 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100672 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700673 // If it's not calling from cameraserver, check the permission only if
674 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
675 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100676 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700677 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700678 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100679 res = cameraInfo->removePermissionEntries(
680 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
681 &tagsRemoved);
682 if (res != OK) {
683 cameraInfo->clear();
684 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
685 " characteristics needing camera permission for device %s: %s (%d)",
686 String8(cameraId).string(), strerror(-res), res);
687 }
688 }
689
690 if (!tagsRemoved.empty()) {
691 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
692 tagsRemoved.data(), tagsRemoved.size());
693 if (res != OK) {
694 cameraInfo->clear();
695 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
696 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
697 strerror(-res), res);
698 }
699 }
700
Zhijun He2b59be82013-09-25 10:14:30 -0700701 return ret;
702}
703
Ruben Brunkcc776712015-02-17 20:18:47 -0800704String8 CameraService::getFormattedCurrentTime() {
705 time_t now = time(nullptr);
706 char formattedTime[64];
707 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
708 return String8(formattedTime);
709}
710
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800711Status CameraService::getCameraVendorTagDescriptor(
712 /*out*/
713 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700714 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800715 if (!mInitialized) {
716 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800717 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800718 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800719 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
720 if (globalDescriptor != nullptr) {
721 *desc = *(globalDescriptor.get());
722 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800723 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800724}
725
Emilian Peev71c73a22017-03-21 16:35:51 +0000726Status CameraService::getCameraVendorTagCache(
727 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
728 ATRACE_CALL();
729 if (!mInitialized) {
730 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
731 return STATUS_ERROR(ERROR_DISCONNECTED,
732 "Camera subsystem not available");
733 }
734 sp<VendorTagDescriptorCache> globalCache =
735 VendorTagDescriptorCache::getGlobalVendorTagCache();
736 if (globalCache != nullptr) {
737 *cache = *(globalCache.get());
738 }
739 return Status::ok();
740}
741
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800742int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700743 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800744
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800745 int deviceVersion = 0;
746
Emilian Peevf53f66e2017-04-11 14:29:43 +0100747 status_t res;
748 hardware::hidl_version maxVersion{0,0};
749 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
750 &maxVersion);
751 if (res != OK) return -1;
752 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800753
Emilian Peevf53f66e2017-04-11 14:29:43 +0100754 hardware::CameraInfo info;
755 if (facing) {
756 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800757 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100758 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800759 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100760
Igor Murashkin634a5152013-02-20 17:15:11 -0800761 return deviceVersion;
762}
763
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800764Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700765 switch(err) {
766 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800767 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800768 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800769 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
770 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800771 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800772 return STATUS_ERROR(ERROR_DISCONNECTED,
773 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700774 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800775 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
776 "Camera HAL encountered error %d: %s",
777 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700778 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800779}
780
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800781Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800782 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700783 const std::optional<String16>& featureId, const String8& cameraId,
784 int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800785 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800786 /*out*/sp<BasicClient>* client) {
787
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700788 // Create CameraClient based on device version reported by the HAL.
789 switch(deviceVersion) {
790 case CAMERA_DEVICE_API_VERSION_1_0:
791 ALOGE("Camera using old HAL version: %d", deviceVersion);
792 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
793 "Camera device \"%s\" HAL version %d no longer supported",
794 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800795 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700796 case CAMERA_DEVICE_API_VERSION_3_0:
797 case CAMERA_DEVICE_API_VERSION_3_1:
798 case CAMERA_DEVICE_API_VERSION_3_2:
799 case CAMERA_DEVICE_API_VERSION_3_3:
800 case CAMERA_DEVICE_API_VERSION_3_4:
801 case CAMERA_DEVICE_API_VERSION_3_5:
802 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800803 if (effectiveApiLevel == API_1) { // Camera1 API route
804 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800805 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800806 cameraId, api1CameraId,
807 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700808 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800809 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800810 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
811 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800812 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
813 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800814 }
815 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700816 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800817 // Should not be reachable
818 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800820 "Camera device \"%s\" has unknown HAL version %d",
821 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800822 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800823 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800824}
825
Ruben Brunk6267b532015-04-30 17:44:07 -0700826String8 CameraService::toString(std::set<userid_t> intSet) {
827 String8 s("");
828 bool first = true;
829 for (userid_t i : intSet) {
830 if (first) {
831 s.appendFormat("%d", i);
832 first = false;
833 } else {
834 s.appendFormat(", %d", i);
835 }
836 }
837 return s;
838}
839
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800840int32_t CameraService::mapToInterface(TorchModeStatus status) {
841 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
842 switch (status) {
843 case TorchModeStatus::NOT_AVAILABLE:
844 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
845 break;
846 case TorchModeStatus::AVAILABLE_OFF:
847 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
848 break;
849 case TorchModeStatus::AVAILABLE_ON:
850 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
851 break;
852 default:
853 ALOGW("Unknown new flash status: %d", status);
854 }
855 return serviceStatus;
856}
857
858CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
859 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
860 switch (status) {
861 case CameraDeviceStatus::NOT_PRESENT:
862 serviceStatus = StatusInternal::NOT_PRESENT;
863 break;
864 case CameraDeviceStatus::PRESENT:
865 serviceStatus = StatusInternal::PRESENT;
866 break;
867 case CameraDeviceStatus::ENUMERATING:
868 serviceStatus = StatusInternal::ENUMERATING;
869 break;
870 default:
871 ALOGW("Unknown new HAL device status: %d", status);
872 }
873 return serviceStatus;
874}
875
876int32_t CameraService::mapToInterface(StatusInternal status) {
877 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
878 switch (status) {
879 case StatusInternal::NOT_PRESENT:
880 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
881 break;
882 case StatusInternal::PRESENT:
883 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
884 break;
885 case StatusInternal::ENUMERATING:
886 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
887 break;
888 case StatusInternal::NOT_AVAILABLE:
889 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
890 break;
891 case StatusInternal::UNKNOWN:
892 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
893 break;
894 default:
895 ALOGW("Unknown new internal device status: %d", status);
896 }
897 return serviceStatus;
898}
899
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800900Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700901 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700902
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800903 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800904 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800905 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800906 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800907 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800908 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900909 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700910 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800911 ).isOk()) {
912 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700913 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800914 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700915}
916
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800917Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700918 /*out*/
919 CameraParameters* parameters) {
920
921 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
922
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800923 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700924
925 if (parameters == NULL) {
926 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800927 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700928 }
929
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 String8 id = String8::format("%d", cameraId);
931
932 // Check if we already have parameters
933 {
934 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700935 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800936 auto cameraState = getCameraState(id);
937 if (cameraState == nullptr) {
938 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800939 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
940 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800941 }
942 CameraParameters p = cameraState->getShimParams();
943 if (!p.isEmpty()) {
944 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800945 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700946 }
947 }
948
Jayant Chowdhary12361932018-08-27 14:46:13 -0700949 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800950 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700951 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800952 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800953 // Error already logged by callee
954 return ret;
955 }
956
957 // Check for parameters again
958 {
959 // Scope for service lock
960 Mutex::Autolock lock(mServiceLock);
961 auto cameraState = getCameraState(id);
962 if (cameraState == nullptr) {
963 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800964 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
965 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -0700966 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800967 CameraParameters p = cameraState->getShimParams();
968 if (!p.isEmpty()) {
969 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800970 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700971 }
972 }
973
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
975 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800976 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700977}
978
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800979// Can camera service trust the caller based on the calling UID?
980static bool isTrustedCallingUid(uid_t uid) {
981 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700982 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800983 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -0700984 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800985 return true;
986 default:
987 return false;
988 }
989}
990
Nicholas Sauera3620332019-04-03 14:05:17 -0700991static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
992 PermissionController pc;
993 uid = pc.getPackageUid(packageName, 0);
994 if (uid <= 0) {
995 ALOGE("Unknown package: '%s'", String8(packageName).string());
996 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
997 return BAD_VALUE;
998 }
999
1000 if (userId < 0) {
1001 ALOGE("Invalid user: %d", userId);
1002 dprintf(err, "Invalid user: %d\n", userId);
1003 return BAD_VALUE;
1004 }
1005
1006 uid = multiuser_get_uid(userId, uid);
1007 return NO_ERROR;
1008}
1009
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001010Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001011 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1012 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001013
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001014#ifdef __BRILLO__
1015 UNUSED(clientName8);
1016 UNUSED(clientUid);
1017 UNUSED(clientPid);
1018 UNUSED(originalClientPid);
1019#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001020 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1021 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001022 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001023 return allowed;
1024 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001025#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001026
Jayant Chowdhary12361932018-08-27 14:46:13 -07001027 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001028
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001029 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001030 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1031 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001032 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1033 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001034 }
1035
Ruben Brunkcc776712015-02-17 20:18:47 -08001036 if (getCameraState(cameraId) == nullptr) {
1037 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1038 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001039 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1040 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 }
1042
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001043 status_t err = checkIfDeviceIsUsable(cameraId);
1044 if (err != NO_ERROR) {
1045 switch(err) {
1046 case -ENODEV:
1047 case -EBUSY:
1048 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1049 "No camera device with ID \"%s\" currently available", cameraId.string());
1050 default:
1051 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1052 "Unknown error connecting to ID \"%s\"", cameraId.string());
1053 }
1054 }
1055 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001056}
1057
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001058Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001059 const String8& clientName8, int& clientUid, int& clientPid,
1060 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001061 int callingPid = CameraThreadState::getCallingPid();
1062 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001064 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001066 clientUid = callingUid;
1067 } else if (!isTrustedCallingUid(callingUid)) {
1068 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1069 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001070 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1071 "Untrusted caller (calling PID %d, UID %d) trying to "
1072 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1073 callingPid, callingUid, cameraId.string(),
1074 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 }
1076
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001077 // Check if we can trust clientPid
1078 if (clientPid == USE_CALLING_PID) {
1079 clientPid = callingPid;
1080 } else if (!isTrustedCallingUid(callingUid)) {
1081 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1082 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001083 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1084 "Untrusted caller (calling PID %d, UID %d) trying to "
1085 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1086 callingPid, callingUid, cameraId.string(),
1087 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001088 }
1089
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001090 if (shouldRejectSystemCameraConnection(cameraId)) {
1091 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1092 cameraId.c_str());
1093 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1094 "available", cameraId.string());
1095 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001096 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1097 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1098 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1099 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1100 "found while trying to query device kind", cameraId.string());
1101
1102 }
1103
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001104 // If it's not calling from cameraserver, check the permission if the
1105 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1106 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001107 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001108 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001109 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001110 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001111 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1112 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1113 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001114 }
1115
Svet Ganova453d0d2018-01-11 15:37:58 -08001116 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001117 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001118 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001119 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1120 clientPid, clientUid);
1121 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001122 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1123 "calling UID %d proc state %" PRId32 ")",
1124 clientName8.string(), clientUid, clientPid, cameraId.string(),
1125 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001126 }
1127
Michael Grooverd1d435a2018-12-18 17:39:42 -08001128 // If sensor privacy is enabled then prevent access to the camera
1129 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1130 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1131 return STATUS_ERROR_FMT(ERROR_DISABLED,
1132 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1133 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1134 }
1135
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001136 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1137 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001138 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001139 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140
Ruben Brunk6267b532015-04-30 17:44:07 -07001141 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001142
Ruben Brunka8ca9152015-04-07 14:23:40 -07001143 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001144 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001145 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001146 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001147 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1148 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1149 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001150 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1151 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1152 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001153 }
1154
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001155 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001156}
1157
1158status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1159 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001160 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001161 if (cameraState == nullptr) {
1162 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1163 cameraId.string());
1164 return -ENODEV;
1165 }
1166
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001167 StatusInternal currentStatus = cameraState->getStatus();
1168 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001169 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1170 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001171 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001172 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001173 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1174 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001175 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001176 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001177
Ruben Brunkcc776712015-02-17 20:18:47 -08001178 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001179}
1180
Ruben Brunkcc776712015-02-17 20:18:47 -08001181void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1182 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001183
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 // Make a descriptor for the incoming client
1185 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1186 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1187
1188 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1189 String8(client->getPackageName()));
1190
1191 if (evicted.size() > 0) {
1192 // This should never happen - clients should already have been removed in disconnect
1193 for (auto& i : evicted) {
1194 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1195 __FUNCTION__, i->getKey().string());
1196 }
1197
1198 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1199 __FUNCTION__);
1200 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001201
1202 // And register a death notification for the client callback. Do
1203 // this last to avoid Binder policy where a nested Binder
1204 // transaction might be pre-empted to service the client death
1205 // notification if the client process dies before linkToDeath is
1206 // invoked.
1207 sp<IBinder> remoteCallback = client->getRemote();
1208 if (remoteCallback != nullptr) {
1209 remoteCallback->linkToDeath(this);
1210 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001211}
1212
1213status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1214 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1215 /*out*/
1216 sp<BasicClient>* client,
1217 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001218 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001219 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001220 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 DescriptorPtr clientDescriptor;
1222 {
1223 if (effectiveApiLevel == API_1) {
1224 // If we are using API1, any existing client for this camera ID with the same remote
1225 // should be returned rather than evicted to allow MediaRecorder to work properly.
1226
1227 auto current = mActiveClientManager.get(cameraId);
1228 if (current != nullptr) {
1229 auto clientSp = current->getValue();
1230 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001231 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1232 ALOGW("CameraService connect called from same client, but with a different"
1233 " API level, evicting prior client...");
1234 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001235 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001236 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 *client = clientSp;
1238 return NO_ERROR;
1239 }
1240 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001241 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001242 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001243
Ruben Brunkcc776712015-02-17 20:18:47 -08001244 // Get current active client PIDs
1245 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1246 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001247
Emilian Peev8131a262017-02-01 12:33:43 +00001248 std::vector<int> priorityScores(ownerPids.size());
1249 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001250
Emilian Peev8131a262017-02-01 12:33:43 +00001251 // Get priority scores of all active PIDs
1252 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1253 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1254 /*out*/&priorityScores[0]);
1255 if (err != OK) {
1256 ALOGE("%s: Priority score query failed: %d",
1257 __FUNCTION__, err);
1258 return err;
1259 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001260
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001262 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001263 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001264 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001265 resource_policy::ClientPriority(priorityScores[i], states[i],
1266 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001267 }
1268 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001269
Ruben Brunkcc776712015-02-17 20:18:47 -08001270 // Get state for the given cameraId
1271 auto state = getCameraState(cameraId);
1272 if (state == nullptr) {
1273 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1274 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001275 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001276 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001277 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001278
1279 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001280 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1282 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001283 priorityScores[priorityScores.size() - 1],
1284 clientPid,
1285 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001286
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001287 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1288
Ruben Brunkcc776712015-02-17 20:18:47 -08001289 // Find clients that would be evicted
1290 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1291
1292 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1293 // background, so we cannot do evictions
1294 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1295 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1296 " priority).", clientPid);
1297
1298 sp<BasicClient> clientSp = clientDescriptor->getValue();
1299 String8 curTime = getFormattedCurrentTime();
1300 auto incompatibleClients =
1301 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1302
1303 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001304 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001305 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001306 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001307
1308 for (auto& i : incompatibleClients) {
1309 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001310 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1311 i->getKey().string(),
1312 String8{i->getValue()->getPackageName()}.string(),
1313 i->getOwnerId(), i->getPriority().getScore(),
1314 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001315 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001316 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001317 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001318 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 }
1320
1321 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001322 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001323 mEventLog.add(msg);
1324
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001325 auto current = mActiveClientManager.get(cameraId);
1326 if (current != nullptr) {
1327 return -EBUSY; // CAMERA_IN_USE
1328 } else {
1329 return -EUSERS; // MAX_CAMERAS_IN_USE
1330 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001331 }
1332
1333 for (auto& i : evicted) {
1334 sp<BasicClient> clientSp = i->getValue();
1335 if (clientSp.get() == nullptr) {
1336 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1337
1338 // TODO: Remove this
1339 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1340 __FUNCTION__);
1341 mActiveClientManager.remove(i);
1342 continue;
1343 }
1344
1345 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1346 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001347 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001348
Ruben Brunkcc776712015-02-17 20:18:47 -08001349 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001350 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001351 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1352 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001353 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001354 i->getOwnerId(), i->getPriority().getScore(),
1355 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001356 packageName.string(), clientPid, clientPriority.getScore(),
1357 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001358
1359 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001360 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001362 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001363 }
1364
Ruben Brunkcc776712015-02-17 20:18:47 -08001365 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1366 // other clients from connecting in mServiceLockWrapper if held
1367 mServiceLock.unlock();
1368
1369 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001370 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001371
1372 // Destroy evicted clients
1373 for (auto& i : evictedClients) {
1374 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001375 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001377
Jayant Chowdhary12361932018-08-27 14:46:13 -07001378 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001379
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001380 for (const auto& i : evictedClients) {
1381 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1382 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1383 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1384 if (ret == TIMED_OUT) {
1385 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1386 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1387 mActiveClientManager.toString().string());
1388 return -EBUSY;
1389 }
1390 if (ret != NO_ERROR) {
1391 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1392 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1393 ret, mActiveClientManager.toString().string());
1394 return ret;
1395 }
1396 }
1397
1398 evictedClients.clear();
1399
Ruben Brunkcc776712015-02-17 20:18:47 -08001400 // Once clients have been disconnected, relock
1401 mServiceLock.lock();
1402
1403 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1404 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1405 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001406 }
1407
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 *partial = clientDescriptor;
1409 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001410}
1411
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001413 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001414 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001415 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001416 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001417 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001418 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001419 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001420
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001421 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001422 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001423
1424 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001426 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001427 clientPackageName, {}, clientUid, clientPid, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001428 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001429
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001430 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001431 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001432 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001433 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001434 }
1435
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001436 *device = client;
1437 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001438}
1439
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001440bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1441 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001442 // If the client is not a vendor client, don't add listener if
1443 // a) the camera is a publicly hidden secure camera OR
1444 // b) the camera is a system only camera and the client doesn't
1445 // have android.permission.SYSTEM_CAMERA permissions.
1446 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1447 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1448 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001449 return true;
1450 }
1451 return false;
1452}
1453
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001454bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1455 // Rules for rejection:
1456 // 1) If cameraserver tries to access this camera device, accept the
1457 // connection.
1458 // 2) The camera device is a publicly hidden secure camera device AND some
1459 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1460 // reject it.
1461 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1462 // and the serving thread is a non hwbinder thread, the client must have
1463 // android.permission.SYSTEM_CAMERA permissions to connect.
1464
1465 int cPid = CameraThreadState::getCallingPid();
1466 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001467 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1468 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001469 // This isn't a known camera ID, so it's not a system camera
1470 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1471 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001472 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001473
1474 // (1) Cameraserver trying to connect, accept.
1475 if (CameraThreadState::getCallingPid() == getpid()) {
1476 return false;
1477 }
1478 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001479 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001480 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1481 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1482 return true;
1483 }
1484 // (3) Here we only check for permissions if it is a system only camera device. This is since
1485 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1486 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1487 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001488 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001489 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1490 !hasPermissionsForSystemCamera(cPid, cUid)) {
1491 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1492 cameraId.c_str());
1493 return true;
1494 }
1495
1496 return false;
1497}
1498
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001499Status CameraService::connectDevice(
1500 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001501 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001502 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001503 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 int clientUid,
1505 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001506 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001507
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001508 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001509 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001510 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001511 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001512 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001513
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001514 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001515 std::string vendorClient =
1516 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1517 clientPackageNameAdj = String16(vendorClient.c_str());
1518 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001519 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001520 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001521 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001522
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001523 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001524 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001525 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001526 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001527 }
1528
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001529 *device = client;
1530 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001531}
1532
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001533template<class CALLBACK, class CLIENT>
1534Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001535 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001536 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001537 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001538 /*out*/sp<CLIENT>& device) {
1539 binder::Status ret = binder::Status::ok();
1540
1541 String8 clientName8(clientPackageName);
1542
1543 int originalClientPid = 0;
1544
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001545 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001546 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001547 static_cast<int>(effectiveApiLevel));
1548
Shuzhen Wang316781a2020-08-18 18:11:01 -07001549 nsecs_t openTimeNs = systemTime();
1550
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001551 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001552 int facing = -1;
1553 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001554 {
1555 // Acquire mServiceLock and prevent other clients from connecting
1556 std::unique_ptr<AutoConditionLock> lock =
1557 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1558
1559 if (lock == nullptr) {
1560 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1561 , clientPid);
1562 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1563 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1564 cameraId.string(), clientName8.string(), clientPid);
1565 }
1566
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001567 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001568 if(!(ret = validateConnectLocked(cameraId, clientName8,
1569 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1570 return ret;
1571 }
1572
1573 // Check the shim parameters after acquiring lock, if they have already been updated and
1574 // we were doing a shim update, return immediately
1575 if (shimUpdateOnly) {
1576 auto cameraState = getCameraState(cameraId);
1577 if (cameraState != nullptr) {
1578 if (!cameraState->getShimParams().isEmpty()) return ret;
1579 }
1580 }
1581
1582 status_t err;
1583
1584 sp<BasicClient> clientTmp = nullptr;
1585 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1586 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1587 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1588 /*out*/&partial)) != NO_ERROR) {
1589 switch (err) {
1590 case -ENODEV:
1591 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1592 "No camera device with ID \"%s\" currently available",
1593 cameraId.string());
1594 case -EBUSY:
1595 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1596 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1597 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001598 case -EUSERS:
1599 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1600 "Too many cameras already open, cannot open camera \"%s\"",
1601 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001602 default:
1603 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1604 "Unexpected error %s (%d) opening camera \"%s\"",
1605 strerror(-err), err, cameraId.string());
1606 }
1607 }
1608
1609 if (clientTmp.get() != nullptr) {
1610 // Handle special case for API1 MediaRecorder where the existing client is returned
1611 device = static_cast<CLIENT*>(clientTmp.get());
1612 return ret;
1613 }
1614
1615 // give flashlight a chance to close devices if necessary.
1616 mFlashlight->prepareDeviceOpen(cameraId);
1617
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001618 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001619 if (facing == -1) {
1620 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1621 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1622 "Unable to get camera device \"%s\" facing", cameraId.string());
1623 }
1624
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001625 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001626 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001627 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001628 clientPid, clientUid, getpid(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001629 deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001630 /*out*/&tmp)).isOk()) {
1631 return ret;
1632 }
1633 client = static_cast<CLIENT*>(tmp.get());
1634
1635 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1636 __FUNCTION__);
1637
Emilian Peevbd8c5032018-02-14 23:05:40 +00001638 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001639 if (err != OK) {
1640 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001641 // Errors could be from the HAL module open call or from AppOpsManager
1642 switch(err) {
1643 case BAD_VALUE:
1644 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1645 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1646 case -EBUSY:
1647 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1648 "Camera \"%s\" is already open", cameraId.string());
1649 case -EUSERS:
1650 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1651 "Too many cameras already open, cannot open camera \"%s\"",
1652 cameraId.string());
1653 case PERMISSION_DENIED:
1654 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1655 "No permission to open camera \"%s\"", cameraId.string());
1656 case -EACCES:
1657 return STATUS_ERROR_FMT(ERROR_DISABLED,
1658 "Camera \"%s\" disabled by policy", cameraId.string());
1659 case -ENODEV:
1660 default:
1661 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1662 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1663 strerror(-err), err);
1664 }
1665 }
1666
1667 // Update shim paremeters for legacy clients
1668 if (effectiveApiLevel == API_1) {
1669 // Assume we have always received a Client subclass for API1
1670 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1671 String8 rawParams = shimClient->getParameters();
1672 CameraParameters params(rawParams);
1673
1674 auto cameraState = getCameraState(cameraId);
1675 if (cameraState != nullptr) {
1676 cameraState->setShimParams(params);
1677 } else {
1678 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1679 __FUNCTION__, cameraId.string());
1680 }
1681 }
1682
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001683 // Set rotate-and-crop override behavior
1684 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1685 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1686 }
1687
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001688 if (shimUpdateOnly) {
1689 // If only updating legacy shim parameters, immediately disconnect client
1690 mServiceLock.unlock();
1691 client->disconnect();
1692 mServiceLock.lock();
1693 } else {
1694 // Otherwise, add client to active clients list
1695 finishConnectLocked(client, partial);
1696 }
1697 } // lock is destroyed, allow further connect calls
1698
1699 // Important: release the mutex here so the client can call back into the service from its
1700 // destructor (can be at the end of the call)
1701 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001702
1703 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1704 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1705 effectiveApiLevel, isNdk, openLatencyMs);
1706
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001707 return ret;
1708}
1709
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001710status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1711 if (offlineClient.get() == nullptr) {
1712 return BAD_VALUE;
1713 }
1714
1715 {
1716 // Acquire mServiceLock and prevent other clients from connecting
1717 std::unique_ptr<AutoConditionLock> lock =
1718 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1719
1720 if (lock == nullptr) {
1721 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1722 , __FUNCTION__, offlineClient->getClientPid());
1723 return TIMED_OUT;
1724 }
1725
1726 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1727 if (onlineClientDesc.get() == nullptr) {
1728 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1729 cameraId.c_str());
1730 return BAD_VALUE;
1731 }
1732
1733 // Offline clients do not evict or conflict with other online devices. Resource sharing
1734 // conflicts are handled by the camera provider which will either succeed or fail before
1735 // reaching this method.
1736 const auto& onlinePriority = onlineClientDesc->getPriority();
1737 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1738 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1739 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1740 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1741
1742 // Allow only one offline device per camera
1743 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1744 if (!incompatibleClients.empty()) {
1745 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1746 return BAD_VALUE;
1747 }
1748
1749 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1750 if (err != OK) {
1751 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1752 return err;
1753 }
1754
1755 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1756 if (evicted.size() > 0) {
1757 for (auto& i : evicted) {
1758 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1759 __FUNCTION__, i->getKey().string());
1760 }
1761
1762 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1763 "properly", __FUNCTION__);
1764
1765 return BAD_VALUE;
1766 }
1767
1768 logConnectedOffline(offlineClientDesc->getKey(),
1769 static_cast<int>(offlineClientDesc->getOwnerId()),
1770 String8(offlineClient->getPackageName()));
1771
1772 sp<IBinder> remoteCallback = offlineClient->getRemote();
1773 if (remoteCallback != nullptr) {
1774 remoteCallback->linkToDeath(this);
1775 }
1776 } // lock is destroyed, allow further connect calls
1777
1778 return OK;
1779}
1780
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001781Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001782 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001783 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001784
1785 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001786 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001787 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001788 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1789 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001790 }
1791
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001792 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001793 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001794
1795 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001796 auto state = getCameraState(id);
1797 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001798 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1800 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001801 }
1802
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001803 StatusInternal cameraStatus = state->getStatus();
1804 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001805 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1806 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001807 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1808 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001809 }
1810
1811 {
1812 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001813 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001814 status_t err = getTorchStatusLocked(id, &status);
1815 if (err != OK) {
1816 if (err == NAME_NOT_FOUND) {
1817 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1818 "Camera \"%s\" does not have a flash unit", id.string());
1819 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001820 ALOGE("%s: getting current torch status failed for camera %s",
1821 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001822 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1823 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1824 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001825 }
1826
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001827 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001828 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001829 ALOGE("%s: torch mode of camera %s is not available because "
1830 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001831 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1832 "Torch for camera \"%s\" is not available due to an existing camera user",
1833 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001834 } else {
1835 ALOGE("%s: torch mode of camera %s is not available due to "
1836 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001837 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1838 "Torch for camera \"%s\" is not available due to insufficient resources",
1839 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001840 }
1841 }
1842 }
1843
Ruben Brunk99e69712015-05-26 17:25:07 -07001844 {
1845 // Update UID map - this is used in the torch status changed callbacks, so must be done
1846 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001847 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001848 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1849 mTorchUidMap[id].first = uid;
1850 mTorchUidMap[id].second = uid;
1851 } else {
1852 // Set the pending UID
1853 mTorchUidMap[id].first = uid;
1854 }
1855 }
1856
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001857 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001858
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001859 if (err != OK) {
1860 int32_t errorCode;
1861 String8 msg;
1862 switch (err) {
1863 case -ENOSYS:
1864 msg = String8::format("Camera \"%s\" has no flashlight",
1865 id.string());
1866 errorCode = ERROR_ILLEGAL_ARGUMENT;
1867 break;
1868 default:
1869 msg = String8::format(
1870 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1871 id.string(), enabled, strerror(-err), err);
1872 errorCode = ERROR_INVALID_OPERATION;
1873 }
1874 ALOGE("%s: %s", __FUNCTION__, msg.string());
1875 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001876 }
1877
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001878 {
1879 // update the link to client's death
1880 Mutex::Autolock al(mTorchClientMapMutex);
1881 ssize_t index = mTorchClientMap.indexOfKey(id);
1882 if (enabled) {
1883 if (index == NAME_NOT_FOUND) {
1884 mTorchClientMap.add(id, clientBinder);
1885 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001886 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001887 mTorchClientMap.replaceValueAt(index, clientBinder);
1888 }
1889 clientBinder->linkToDeath(this);
1890 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001891 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001892 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001893 }
1894
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001895 int clientPid = CameraThreadState::getCallingPid();
1896 const char *id_cstr = id.c_str();
1897 const char *torchState = enabled ? "on" : "off";
1898 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1899 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001900 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001901}
1902
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001903Status CameraService::notifySystemEvent(int32_t eventId,
1904 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001905 const int pid = CameraThreadState::getCallingPid();
1906 const int selfPid = getpid();
1907
1908 // Permission checks
1909 if (pid != selfPid) {
1910 // Ensure we're being called by system_server, or similar process with
1911 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001912 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001913 const int uid = CameraThreadState::getCallingUid();
1914 ALOGE("Permission Denial: cannot send updates to camera service about system"
1915 " events from pid=%d, uid=%d", pid, uid);
1916 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001917 "No permission to send updates to camera service about system events"
1918 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001919 }
1920 }
1921
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001922 ATRACE_CALL();
1923
Ruben Brunk36597b22015-03-20 22:15:57 -07001924 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001925 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001926 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001927 // from a system server crash
1928 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001929 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001930 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001931 break;
1932 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001933 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001934 default: {
1935 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1936 eventId);
1937 break;
1938 }
1939 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001940 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001941}
1942
Emilian Peev53722fa2019-02-22 17:47:20 -08001943void CameraService::notifyMonitoredUids() {
1944 Mutex::Autolock lock(mStatusListenerLock);
1945
1946 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001947 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08001948 if (!ret.isOk()) {
1949 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1950 ret.exceptionCode());
1951 }
1952 }
1953}
1954
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001955Status CameraService::notifyDeviceStateChange(int64_t newState) {
1956 const int pid = CameraThreadState::getCallingPid();
1957 const int selfPid = getpid();
1958
1959 // Permission checks
1960 if (pid != selfPid) {
1961 // Ensure we're being called by system_server, or similar process with
1962 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001963 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08001964 const int uid = CameraThreadState::getCallingUid();
1965 ALOGE("Permission Denial: cannot send updates to camera service about device"
1966 " state changes from pid=%d, uid=%d", pid, uid);
1967 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1968 "No permission to send updates to camera service about device state"
1969 " changes from pid=%d, uid=%d", pid, uid);
1970 }
1971 }
1972
1973 ATRACE_CALL();
1974
1975 using hardware::camera::provider::V2_5::DeviceState;
1976 hardware::hidl_bitfield<DeviceState> newDeviceState{};
1977 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1978 newDeviceState |= DeviceState::BACK_COVERED;
1979 }
1980 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1981 newDeviceState |= DeviceState::FRONT_COVERED;
1982 }
1983 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1984 newDeviceState |= DeviceState::FOLDED;
1985 }
1986 // Only map vendor bits directly
1987 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1988 newDeviceState |= vendorBits;
1989
1990 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1991 Mutex::Autolock l(mServiceLock);
1992 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1993
1994 return Status::ok();
1995}
1996
Jayant Chowdharycad23c22020-03-10 15:04:59 -07001997 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08001998 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
1999 ATRACE_CALL();
2000 if (!concurrentCameraIds) {
2001 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2002 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2003 }
2004
2005 if (!mInitialized) {
2006 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2007 return STATUS_ERROR(ERROR_DISCONNECTED,
2008 "Camera subsystem is not available");
2009 }
2010 // First call into the provider and get the set of concurrent camera
2011 // combinations
2012 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002013 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002014 for (auto &combination : concurrentCameraCombinations) {
2015 std::vector<std::string> validCombination;
2016 for (auto &cameraId : combination) {
2017 // if the camera state is not present, skip
2018 String8 cameraIdStr(cameraId.c_str());
2019 auto state = getCameraState(cameraIdStr);
2020 if (state == nullptr) {
2021 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2022 continue;
2023 }
2024 StatusInternal status = state->getStatus();
2025 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2026 continue;
2027 }
2028 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2029 continue;
2030 }
2031 validCombination.push_back(cameraId);
2032 }
2033 if (validCombination.size() != 0) {
2034 concurrentCameraIds->push_back(std::move(validCombination));
2035 }
2036 }
2037 return Status::ok();
2038}
2039
2040Status CameraService::isConcurrentSessionConfigurationSupported(
2041 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2042 /*out*/bool* isSupported) {
2043 if (!isSupported) {
2044 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2045 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2046 }
2047
2048 if (!mInitialized) {
2049 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2050 return STATUS_ERROR(ERROR_DISCONNECTED,
2051 "Camera subsystem is not available");
2052 }
2053
2054 // Check for camera permissions
2055 int callingPid = CameraThreadState::getCallingPid();
2056 int callingUid = CameraThreadState::getCallingUid();
2057 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2058 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2059 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2060 "android.permission.CAMERA needed to call"
2061 "isConcurrentSessionConfigurationSupported");
2062 }
2063
2064 status_t res =
2065 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2066 cameraIdsAndSessionConfigurations, isSupported);
2067 if (res != OK) {
2068 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2069 "support %s (%d)", strerror(-res), res);
2070 }
2071 return Status::ok();
2072}
2073
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002074Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2075 /*out*/
2076 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002077 return addListenerHelper(listener, cameraStatuses);
2078}
2079
2080Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2081 /*out*/
2082 std::vector<hardware::CameraStatus> *cameraStatuses,
2083 bool isVendorListener) {
2084
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002085 ATRACE_CALL();
2086
Igor Murashkinbfc99152013-02-27 12:55:20 -08002087 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002088
Ruben Brunk3450ba72015-06-16 11:00:37 -07002089 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002090 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002091 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002092 }
2093
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002094 auto clientUid = CameraThreadState::getCallingUid();
2095 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002096 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2097 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002098
Igor Murashkinbfc99152013-02-27 12:55:20 -08002099 Mutex::Autolock lock(mServiceLock);
2100
Ruben Brunkcc776712015-02-17 20:18:47 -08002101 {
2102 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002103 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002104 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002105 ALOGW("%s: Tried to add listener %p which was already subscribed",
2106 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002107 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002108 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002109 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002110
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002111 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002112 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2113 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002114 auto ret = serviceListener->initialize();
2115 if (ret != NO_ERROR) {
2116 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2117 strerror(-ret), ret);
2118 ALOGE("%s: %s", __FUNCTION__, msg.string());
2119 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2120 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002121 // The listener still needs to be added to the list of listeners, regardless of what
2122 // permissions the listener process has / whether it is a vendor listener. Since it might be
2123 // eligible to listen to other camera ids.
2124 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002125 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002126 }
2127
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002128 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002129 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002130 Mutex::Autolock lock(mCameraStatesLock);
2131 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002132 cameraStatuses->emplace_back(i.first,
2133 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002134 }
2135 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002136 // Remove the camera statuses that should be hidden from the client, we do
2137 // this after collecting the states in order to avoid holding
2138 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2139 // the same time.
2140 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2141 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2142 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2143 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2144 ALOGE("%s: Invalid camera id %s, skipping status update",
2145 __FUNCTION__, s.cameraId.c_str());
2146 return true;
2147 }
2148 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2149 clientUid);}), cameraStatuses->end());
2150
Igor Murashkincba2c162013-03-20 15:56:31 -07002151
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002152 /*
2153 * Immediately signal current torch status to this listener only
2154 * This may be a subset of all the devices, so don't include it in the response directly
2155 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002156 {
2157 Mutex::Autolock al(mTorchStatusMutex);
2158 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002159 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002160 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002161 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002162 }
2163
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002164 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002165}
Ruben Brunkcc776712015-02-17 20:18:47 -08002166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002167Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002168 ATRACE_CALL();
2169
Igor Murashkinbfc99152013-02-27 12:55:20 -08002170 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2171
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002172 if (listener == 0) {
2173 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002174 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002175 }
2176
Igor Murashkinbfc99152013-02-27 12:55:20 -08002177 Mutex::Autolock lock(mServiceLock);
2178
Ruben Brunkcc776712015-02-17 20:18:47 -08002179 {
2180 Mutex::Autolock lock(mStatusListenerLock);
2181 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002182 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2183 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2184 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002185 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002186 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002187 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002188 }
2189 }
2190
2191 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2192 __FUNCTION__, listener.get());
2193
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002194 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002195}
2196
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002197Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002198
2199 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002200 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2201
2202 if (parameters == NULL) {
2203 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002204 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002205 }
2206
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002207 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002208
2209 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002210 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002211 // Error logged by caller
2212 return ret;
2213 }
2214
2215 String8 shimParamsString8 = shimParams.flatten();
2216 String16 shimParamsString16 = String16(shimParamsString8);
2217
2218 *parameters = shimParamsString16;
2219
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002221}
2222
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002223Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2224 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002225 ATRACE_CALL();
2226
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002227 const String8 id = String8(cameraId);
2228
2229 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002230
2231 switch (apiVersion) {
2232 case API_VERSION_1:
2233 case API_VERSION_2:
2234 break;
2235 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002236 String8 msg = String8::format("Unknown API version %d", apiVersion);
2237 ALOGE("%s: %s", __FUNCTION__, msg.string());
2238 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002239 }
2240
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002241 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002242 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 case CAMERA_DEVICE_API_VERSION_1_0:
2244 case CAMERA_DEVICE_API_VERSION_3_0:
2245 case CAMERA_DEVICE_API_VERSION_3_1:
2246 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002247 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2248 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 *isSupported = false;
2250 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002251 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2252 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 *isSupported = true;
2254 }
2255 break;
2256 case CAMERA_DEVICE_API_VERSION_3_2:
2257 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002258 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002259 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002260 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002261 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2262 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002263 *isSupported = true;
2264 break;
2265 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002266 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002267 ALOGE("%s: %s", __FUNCTION__, msg.string());
2268 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002269 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002270 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002271 String8 msg = String8::format("Unknown device version %x for device %s",
2272 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002273 ALOGE("%s: %s", __FUNCTION__, msg.string());
2274 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2275 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002276 }
2277
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002278 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002279}
2280
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002281Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2282 /*out*/ bool *isSupported) {
2283 ATRACE_CALL();
2284
2285 const String8 id = String8(cameraId);
2286
2287 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2288 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2289
2290 return Status::ok();
2291}
2292
Ruben Brunkcc776712015-02-17 20:18:47 -08002293void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002294 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002295 for (auto& i : mActiveClientManager.getAll()) {
2296 auto clientSp = i->getValue();
2297 if (clientSp.get() == client) {
2298 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002299 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002300 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002301 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002302}
2303
Ruben Brunkcc776712015-02-17 20:18:47 -08002304bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002305 bool ret = false;
2306 {
2307 // Acquire mServiceLock and prevent other clients from connecting
2308 std::unique_ptr<AutoConditionLock> lock =
2309 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002310
Igor Murashkin634a5152013-02-20 17:15:11 -08002311
Ruben Brunkcc776712015-02-17 20:18:47 -08002312 std::vector<sp<BasicClient>> evicted;
2313 for (auto& i : mActiveClientManager.getAll()) {
2314 auto clientSp = i->getValue();
2315 if (clientSp.get() == nullptr) {
2316 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2317 mActiveClientManager.remove(i);
2318 continue;
2319 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002320 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002321 mActiveClientManager.remove(i);
2322 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002323
Ruben Brunkcc776712015-02-17 20:18:47 -08002324 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002325 clientSp->notifyError(
2326 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002327 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002328 }
2329 }
2330
Ruben Brunkcc776712015-02-17 20:18:47 -08002331 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2332 // other clients from connecting in mServiceLockWrapper if held
2333 mServiceLock.unlock();
2334
Ruben Brunk36597b22015-03-20 22:15:57 -07002335 // Do not clear caller identity, remote caller should be client proccess
2336
Ruben Brunkcc776712015-02-17 20:18:47 -08002337 for (auto& i : evicted) {
2338 if (i.get() != nullptr) {
2339 i->disconnect();
2340 ret = true;
2341 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002342 }
2343
Ruben Brunkcc776712015-02-17 20:18:47 -08002344 // Reacquire mServiceLock
2345 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002346
Ruben Brunkcc776712015-02-17 20:18:47 -08002347 } // lock is destroyed, allow further connect calls
2348
2349 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002350}
2351
Ruben Brunkcc776712015-02-17 20:18:47 -08002352std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2353 const String8& cameraId) const {
2354 std::shared_ptr<CameraState> state;
2355 {
2356 Mutex::Autolock lock(mCameraStatesLock);
2357 auto iter = mCameraStates.find(cameraId);
2358 if (iter != mCameraStates.end()) {
2359 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 }
2361 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002362 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363}
2364
Ruben Brunkcc776712015-02-17 20:18:47 -08002365sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2366 // Remove from active clients list
2367 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2368 if (clientDescriptorPtr == nullptr) {
2369 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2370 cameraId.string());
2371 return sp<BasicClient>{nullptr};
2372 }
2373
2374 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002375}
2376
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002377void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002378 // Acquire mServiceLock and prevent other clients from connecting
2379 std::unique_ptr<AutoConditionLock> lock =
2380 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2381
Ruben Brunk6267b532015-04-30 17:44:07 -07002382 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002383 for (size_t i = 0; i < newUserIds.size(); i++) {
2384 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002385 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002386 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002387 return;
2388 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002389 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002390 }
2391
Ruben Brunka8ca9152015-04-07 14:23:40 -07002392
Ruben Brunk6267b532015-04-30 17:44:07 -07002393 if (newAllowedUsers == mAllowedUsers) {
2394 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2395 return;
2396 }
2397
2398 logUserSwitch(mAllowedUsers, newAllowedUsers);
2399
2400 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002401
2402 // Current user has switched, evict all current clients.
2403 std::vector<sp<BasicClient>> evicted;
2404 for (auto& i : mActiveClientManager.getAll()) {
2405 auto clientSp = i->getValue();
2406
2407 if (clientSp.get() == nullptr) {
2408 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2409 continue;
2410 }
2411
Ruben Brunk6267b532015-04-30 17:44:07 -07002412 // Don't evict clients that are still allowed.
2413 uid_t clientUid = clientSp->getClientUid();
2414 userid_t clientUserId = multiuser_get_user_id(clientUid);
2415 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2416 continue;
2417 }
2418
Ruben Brunk36597b22015-03-20 22:15:57 -07002419 evicted.push_back(clientSp);
2420
2421 String8 curTime = getFormattedCurrentTime();
2422
2423 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2424 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002425
Ruben Brunk36597b22015-03-20 22:15:57 -07002426 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002427 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002428 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2429 " to user switch.", i->getKey().string(),
2430 String8{clientSp->getPackageName()}.string(),
2431 i->getOwnerId(), i->getPriority().getScore(),
2432 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002433
2434 }
2435
2436 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2437 // blocking other clients from connecting in mServiceLockWrapper if held.
2438 mServiceLock.unlock();
2439
2440 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002441 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002442
2443 for (auto& i : evicted) {
2444 i->disconnect();
2445 }
2446
Jayant Chowdhary12361932018-08-27 14:46:13 -07002447 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002448
2449 // Reacquire mServiceLock
2450 mServiceLock.lock();
2451}
Ruben Brunkcc776712015-02-17 20:18:47 -08002452
Ruben Brunka8ca9152015-04-07 14:23:40 -07002453void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002454 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002455 Mutex::Autolock l(mLogLock);
2456 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457}
2458
Ruben Brunka8ca9152015-04-07 14:23:40 -07002459void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002460 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002461 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002462 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002463 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002464}
2465
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002466void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2467 const char* clientPackage) {
2468 // Log the clients evicted
2469 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2470 cameraId, clientPackage, clientPid));
2471}
2472
Ruben Brunka8ca9152015-04-07 14:23:40 -07002473void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002474 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002475 // Log the clients evicted
2476 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002477 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002478}
2479
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002480void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2481 const char* clientPackage) {
2482 // Log the clients evicted
2483 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2484 clientPackage, clientPid));
2485}
2486
Ruben Brunka8ca9152015-04-07 14:23:40 -07002487void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002488 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002489 // Log the client rejected
2490 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002491 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002492}
2493
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002494void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2495 // Log torch event
2496 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2497 torchState, clientPid));
2498}
2499
Ruben Brunk6267b532015-04-30 17:44:07 -07002500void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2501 const std::set<userid_t>& newUserIds) {
2502 String8 newUsers = toString(newUserIds);
2503 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002504 if (oldUsers.size() == 0) {
2505 oldUsers = "<None>";
2506 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002507 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002508 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002509 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002510}
2511
2512void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2513 // Log the device removal
2514 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2515}
2516
2517void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2518 // Log the device removal
2519 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2520}
2521
2522void CameraService::logClientDied(int clientPid, const char* reason) {
2523 // Log the device removal
2524 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002525}
2526
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002527void CameraService::logServiceError(const char* msg, int errorCode) {
2528 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002529 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002530}
2531
Ruben Brunk36597b22015-03-20 22:15:57 -07002532status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2533 uint32_t flags) {
2534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 // Permission checks
2536 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002537 case SHELL_COMMAND_TRANSACTION: {
2538 int in = data.readFileDescriptor();
2539 int out = data.readFileDescriptor();
2540 int err = data.readFileDescriptor();
2541 int argc = data.readInt32();
2542 Vector<String16> args;
2543 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2544 args.add(data.readString16());
2545 }
2546 sp<IBinder> unusedCallback;
2547 sp<IResultReceiver> resultReceiver;
2548 status_t status;
2549 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2550 return status;
2551 }
2552 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2553 return status;
2554 }
2555 status = shellCommand(in, out, err, args);
2556 if (resultReceiver != nullptr) {
2557 resultReceiver->send(status);
2558 }
2559 return NO_ERROR;
2560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 }
2562
2563 return BnCameraService::onTransact(code, data, reply, flags);
2564}
2565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566// We share the media players for shutter and recording sound for all clients.
2567// A reference count is kept to determine when we will actually release the
2568// media players.
2569
Jaekyun Seokef498052018-03-23 13:09:44 +09002570sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2571 sp<MediaPlayer> mp = new MediaPlayer();
2572 status_t error;
2573 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002574 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002575 error = mp->prepare();
2576 }
2577 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002578 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002579 mp->disconnect();
2580 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002581 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 }
2583 return mp;
2584}
2585
username5755fea2018-12-27 09:48:08 +08002586void CameraService::increaseSoundRef() {
2587 Mutex::Autolock lock(mSoundLock);
2588 mSoundRef++;
2589}
2590
2591void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002592 ATRACE_CALL();
2593
username5755fea2018-12-27 09:48:08 +08002594 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2595 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2596 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2597 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2598 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2599 }
2600 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2601 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2602 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2603 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002604 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002605 }
2606 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2607 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2608 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2609 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2610 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612}
2613
username5755fea2018-12-27 09:48:08 +08002614void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002616 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 if (--mSoundRef) return;
2618
2619 for (int i = 0; i < NUM_SOUNDS; i++) {
2620 if (mSoundPlayer[i] != 0) {
2621 mSoundPlayer[i]->disconnect();
2622 mSoundPlayer[i].clear();
2623 }
2624 }
2625}
2626
2627void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002628 ATRACE_CALL();
2629
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 LOG1("playSound(%d)", kind);
2631 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002632 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 sp<MediaPlayer> player = mSoundPlayer[kind];
2634 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002635 player->seekTo(0);
2636 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 }
2638}
2639
2640// ----------------------------------------------------------------------------
2641
2642CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002643 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002644 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002645 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002646 const String8& cameraIdStr,
2647 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002648 int clientPid, uid_t clientUid,
2649 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002650 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002651 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002652 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002653 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002654 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002655 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002656 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002657{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002658 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002659 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002661 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662
username5755fea2018-12-27 09:48:08 +08002663 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002664
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002665 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666}
2667
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668// tear down the client
2669CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002670 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002671 mDestructionStarted = true;
2672
username5755fea2018-12-27 09:48:08 +08002673 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002674 // unconditionally disconnect. function is idempotent
2675 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676}
2677
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002678sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2679
Igor Murashkin634a5152013-02-20 17:15:11 -08002680CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002681 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002682 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002683 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002684 int clientPid, uid_t clientUid,
2685 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002686 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002687 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002688 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002689 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002690 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002691 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002692 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002693{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002694 if (sCameraService == nullptr) {
2695 sCameraService = cameraService;
2696 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002697 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002698 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002699
2700 // In some cases the calling code has no access to the package it runs under.
2701 // For example, NDK camera API.
2702 // In this case we will get the packages for the calling UID and pick the first one
2703 // for attributing the app op. This will work correctly for runtime permissions
2704 // as for legacy apps we will toggle the app op for all packages in the UID.
2705 // The caveat is that the operation may be attributed to the wrong package and
2706 // stats based on app ops may be slightly off.
2707 if (mClientPackageName.size() <= 0) {
2708 sp<IServiceManager> sm = defaultServiceManager();
2709 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2710 if (binder == 0) {
2711 ALOGE("Cannot get permission service");
2712 // Leave mClientPackageName unchanged (empty) and the further interaction
2713 // with camera will fail in BasicClient::startCameraOps
2714 return;
2715 }
2716
2717 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2718 Vector<String16> packages;
2719
2720 permCtrl->getPackagesForUid(mClientUid, packages);
2721
2722 if (packages.isEmpty()) {
2723 ALOGE("No packages for calling UID");
2724 // Leave mClientPackageName unchanged (empty) and the further interaction
2725 // with camera will fail in BasicClient::startCameraOps
2726 return;
2727 }
2728 mClientPackageName = packages[0];
2729 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002730 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002731 mAppOpsManager = std::make_unique<AppOpsManager>();
2732 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002733
2734 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002735}
2736
2737CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002738 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002739 mDestructionStarted = true;
2740}
2741
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002742binder::Status CameraService::BasicClient::disconnect() {
2743 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002744 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002745 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002746 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002747 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002748
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002749 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002750 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002751 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2752 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002753
2754 sp<IBinder> remote = getRemote();
2755 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002756 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002757 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002758
2759 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002760 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002761 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2762 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2763 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002764
Igor Murashkincba2c162013-03-20 15:56:31 -07002765 // client shouldn't be able to call into us anymore
2766 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002767
2768 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002769}
2770
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002771status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2772 // No dumping of clients directly over Binder,
2773 // must go through CameraService::dump
2774 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002775 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002776 return OK;
2777}
2778
Ruben Brunkcc776712015-02-17 20:18:47 -08002779String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002780 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002781}
2782
2783
2784int CameraService::BasicClient::getClientPid() const {
2785 return mClientPid;
2786}
2787
Ruben Brunk6267b532015-04-30 17:44:07 -07002788uid_t CameraService::BasicClient::getClientUid() const {
2789 return mClientUid;
2790}
2791
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002792bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2793 // Defaults to API2.
2794 return level == API_2;
2795}
2796
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002797status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002798 {
2799 Mutex::Autolock l(mAudioRestrictionLock);
2800 mAudioRestriction = mode;
2801 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002802 sCameraService->updateAudioRestriction();
2803 return OK;
2804}
2805
2806int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002807 return sCameraService->updateAudioRestriction();
2808}
2809
2810int32_t CameraService::BasicClient::getAudioRestriction() const {
2811 Mutex::Autolock l(mAudioRestrictionLock);
2812 return mAudioRestriction;
2813}
2814
2815bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2816 switch (mode) {
2817 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2818 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2819 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2820 return true;
2821 default:
2822 return false;
2823 }
2824}
2825
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002826status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002827 ATRACE_CALL();
2828
Igor Murashkine6800ce2013-03-04 17:25:57 -08002829 {
2830 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002831 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002832 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002833 if (mAppOpsManager != nullptr) {
2834 // Notify app ops that the camera is not available
2835 mOpsCallback = new OpsCallback(this);
2836 int32_t res;
2837 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2838 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002839 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2840 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2841 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002842
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002843 if (res == AppOpsManager::MODE_ERRORED) {
2844 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2845 mCameraIdStr.string(), String8(mClientPackageName).string());
2846 return PERMISSION_DENIED;
2847 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002848
Shuzhen Wang2c656792020-04-13 17:36:49 -07002849 // If the calling Uid is trusted (a native service), the AppOpsManager could
2850 // return MODE_IGNORED. Do not treat such case as error.
2851 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002852 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2853 mCameraIdStr.string(), String8(mClientPackageName).string());
2854 // Return the same error as for device policy manager rejection
2855 return -EACCES;
2856 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002857 }
2858
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002859 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002860
2861 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002862 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002863
Emilian Peev53722fa2019-02-22 17:47:20 -08002864 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2865
Shuzhen Wang695044d2020-03-06 09:02:23 -08002866 // Notify listeners of camera open/close status
2867 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2868
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002869 return OK;
2870}
2871
2872status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002873 ATRACE_CALL();
2874
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002875 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002876 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002877 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002878 if (mAppOpsManager != nullptr) {
2879 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002880 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002881 mOpsActive = false;
2882 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002883 // This function is called when a client disconnects. This should
2884 // release the camera, but actually only if it was in a proper
2885 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002886 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002887 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002888
Ruben Brunkcc776712015-02-17 20:18:47 -08002889 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002890 sCameraService->updateStatus(StatusInternal::PRESENT,
2891 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002892 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002893 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002894 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2895 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002896 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002897 mOpsCallback.clear();
2898
Emilian Peev53722fa2019-02-22 17:47:20 -08002899 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2900
Shuzhen Wang695044d2020-03-06 09:02:23 -08002901 // Notify listeners of camera open/close status
2902 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2903
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002904 return OK;
2905}
2906
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002907void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002908 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002909 if (mAppOpsManager == nullptr) {
2910 return;
2911 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002912 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002913 if (op != AppOpsManager::OP_CAMERA) {
2914 ALOGW("Unexpected app ops notification received: %d", op);
2915 return;
2916 }
2917
2918 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002919 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002920 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002921 ALOGV("checkOp returns: %d, %s ", res,
2922 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2923 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2924 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2925 "UNKNOWN");
2926
2927 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002928 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002929 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08002930 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002931 }
2932}
2933
Svet Ganova453d0d2018-01-11 15:37:58 -08002934void CameraService::BasicClient::block() {
2935 ATRACE_CALL();
2936
2937 // Reset the client PID to allow server-initiated disconnect,
2938 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07002939 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08002940 CaptureResultExtras resultExtras; // a dummy result (invalid)
2941 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2942 disconnect();
2943}
2944
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945// ----------------------------------------------------------------------------
2946
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002947void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07002948 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002949 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002950 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07002951 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2952 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2953 api1ErrorCode = CAMERA_ERROR_DISABLED;
2954 }
2955 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07002956 } else {
2957 ALOGE("mRemoteCallback is NULL!!");
2958 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002959}
2960
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002961// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002962binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002963 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002964 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08002965}
2966
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002967bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2968 return level == API_1;
2969}
2970
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002971CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2972 mClient(client) {
2973}
2974
2975void CameraService::Client::OpsCallback::opChanged(int32_t op,
2976 const String16& packageName) {
2977 sp<BasicClient> client = mClient.promote();
2978 if (client != NULL) {
2979 client->opChanged(op, packageName);
2980 }
2981}
2982
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08002984// UidPolicy
2985// ----------------------------------------------------------------------------
2986
2987void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002988 Mutex::Autolock _l(mUidLock);
2989
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002990 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07002991 status_t res = mAm.linkToDeath(this);
2992 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08002993 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08002994 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08002995 ActivityManager::PROCESS_STATE_UNKNOWN,
2996 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002997 if (res == OK) {
2998 mRegistered = true;
2999 ALOGV("UidPolicy: Registered with ActivityManager");
3000 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003001}
3002
3003void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003004 Mutex::Autolock _l(mUidLock);
3005
Steven Moreland2f348142019-07-02 15:59:07 -07003006 mAm.unregisterUidObserver(this);
3007 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003008 mRegistered = false;
3009 mActiveUids.clear();
3010 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003011}
3012
3013void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3014 onUidIdle(uid, disabled);
3015}
3016
3017void CameraService::UidPolicy::onUidActive(uid_t uid) {
3018 Mutex::Autolock _l(mUidLock);
3019 mActiveUids.insert(uid);
3020}
3021
3022void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3023 bool deleted = false;
3024 {
3025 Mutex::Autolock _l(mUidLock);
3026 if (mActiveUids.erase(uid) > 0) {
3027 deleted = true;
3028 }
3029 }
3030 if (deleted) {
3031 sp<CameraService> service = mService.promote();
3032 if (service != nullptr) {
3033 service->blockClientsForUid(uid);
3034 }
3035 }
3036}
3037
Emilian Peev53722fa2019-02-22 17:47:20 -08003038void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003039 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003040 bool procStateChange = false;
3041 {
3042 Mutex::Autolock _l(mUidLock);
3043 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3044 (mMonitoredUids[uid].first != procState)) {
3045 mMonitoredUids[uid].first = procState;
3046 procStateChange = true;
3047 }
3048 }
3049
3050 if (procStateChange) {
3051 sp<CameraService> service = mService.promote();
3052 if (service != nullptr) {
3053 service->notifyMonitoredUids();
3054 }
3055 }
3056}
3057
3058void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3059 Mutex::Autolock _l(mUidLock);
3060 auto it = mMonitoredUids.find(uid);
3061 if (it != mMonitoredUids.end()) {
3062 it->second.second++;
3063 } else {
3064 mMonitoredUids.emplace(
3065 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3066 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3067 }
3068}
3069
3070void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3071 Mutex::Autolock _l(mUidLock);
3072 auto it = mMonitoredUids.find(uid);
3073 if (it != mMonitoredUids.end()) {
3074 it->second.second--;
3075 if (it->second.second == 0) {
3076 mMonitoredUids.erase(it);
3077 }
3078 } else {
3079 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3080 }
3081}
3082
Svet Ganov7b4ab782018-03-25 12:48:10 -07003083bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003084 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003085 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003086}
3087
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003088static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3089static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003090
Svet Ganov7b4ab782018-03-25 12:48:10 -07003091bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003092 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003093 // If activity manager is unreachable, assume everything is active
3094 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003095 return true;
3096 }
3097 auto it = mOverrideUids.find(uid);
3098 if (it != mOverrideUids.end()) {
3099 return it->second;
3100 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003101 bool active = mActiveUids.find(uid) != mActiveUids.end();
3102 if (!active) {
3103 // We want active UIDs to always access camera with their first attempt since
3104 // there is no guarantee the app is robustly written and would retry getting
3105 // the camera on failure. The inverse case is not a problem as we would take
3106 // camera away soon once we get the callback that the uid is no longer active.
3107 ActivityManager am;
3108 // Okay to access with a lock held as UID changes are dispatched without
3109 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003110 int64_t startTimeMillis = 0;
3111 do {
3112 // TODO: Fix this b/109950150!
3113 // Okay this is a hack. There is a race between the UID turning active and
3114 // activity being resumed. The proper fix is very risky, so we temporary add
3115 // some polling which should happen pretty rarely anyway as the race is hard
3116 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003117 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003118 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003119 if (active) {
3120 break;
3121 }
3122 if (startTimeMillis <= 0) {
3123 startTimeMillis = uptimeMillis();
3124 }
3125 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003126 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003127 if (remainingTimeMillis <= 0) {
3128 break;
3129 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003130 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3131
3132 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003133 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003134 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003135 } while (true);
3136
Svet Ganov7b4ab782018-03-25 12:48:10 -07003137 if (active) {
3138 // Now that we found out the UID is actually active, cache that
3139 mActiveUids.insert(uid);
3140 }
3141 }
3142 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003143}
3144
Varun Shahb42f1eb2019-04-16 14:45:13 -07003145int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3146 Mutex::Autolock _l(mUidLock);
3147 return getProcStateLocked(uid);
3148}
3149
3150int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3151 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3152 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3153 procState = mMonitoredUids[uid].first;
3154 }
3155 return procState;
3156}
3157
Svet Ganov7b4ab782018-03-25 12:48:10 -07003158void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3159 String16 callingPackage, bool active) {
3160 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003161}
3162
Svet Ganov7b4ab782018-03-25 12:48:10 -07003163void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3164 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003165}
3166
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003167void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3168 Mutex::Autolock _l(mUidLock);
3169 ALOGV("UidPolicy: ActivityManager has died");
3170 mRegistered = false;
3171 mActiveUids.clear();
3172}
3173
Svet Ganov7b4ab782018-03-25 12:48:10 -07003174void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3175 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003176 bool wasActive = false;
3177 bool isActive = false;
3178 {
3179 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003180 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003181 mOverrideUids.erase(uid);
3182 if (insert) {
3183 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3184 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003185 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003186 }
3187 if (wasActive != isActive && !isActive) {
3188 sp<CameraService> service = mService.promote();
3189 if (service != nullptr) {
3190 service->blockClientsForUid(uid);
3191 }
3192 }
3193}
3194
3195// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003196// SensorPrivacyPolicy
3197// ----------------------------------------------------------------------------
3198void CameraService::SensorPrivacyPolicy::registerSelf() {
3199 Mutex::Autolock _l(mSensorPrivacyLock);
3200 if (mRegistered) {
3201 return;
3202 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003203 mSpm.addSensorPrivacyListener(this);
3204 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3205 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003206 if (res == OK) {
3207 mRegistered = true;
3208 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3209 }
3210}
3211
3212void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3213 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003214 mSpm.removeSensorPrivacyListener(this);
3215 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003216 mRegistered = false;
3217 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3218}
3219
3220bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3221 Mutex::Autolock _l(mSensorPrivacyLock);
3222 return mSensorPrivacyEnabled;
3223}
3224
3225binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3226 {
3227 Mutex::Autolock _l(mSensorPrivacyLock);
3228 mSensorPrivacyEnabled = enabled;
3229 }
3230 // if sensor privacy is enabled then block all clients from accessing the camera
3231 if (enabled) {
3232 sp<CameraService> service = mService.promote();
3233 if (service != nullptr) {
3234 service->blockAllClients();
3235 }
3236 }
3237 return binder::Status::ok();
3238}
3239
3240void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3241 Mutex::Autolock _l(mSensorPrivacyLock);
3242 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3243 mRegistered = false;
3244}
3245
3246// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003247// CameraState
3248// ----------------------------------------------------------------------------
3249
3250CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003251 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3252 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3253 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003254
3255CameraService::CameraState::~CameraState() {}
3256
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003257CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003258 Mutex::Autolock lock(mStatusLock);
3259 return mStatus;
3260}
3261
Shuzhen Wang43858162020-01-10 13:42:15 -08003262std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3263 Mutex::Autolock lock(mStatusLock);
3264 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3265 return res;
3266}
3267
Ruben Brunkcc776712015-02-17 20:18:47 -08003268CameraParameters CameraService::CameraState::getShimParams() const {
3269 return mShimParams;
3270}
3271
3272void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3273 mShimParams = params;
3274}
3275
3276int CameraService::CameraState::getCost() const {
3277 return mCost;
3278}
3279
3280std::set<String8> CameraService::CameraState::getConflicting() const {
3281 return mConflicting;
3282}
3283
3284String8 CameraService::CameraState::getId() const {
3285 return mId;
3286}
3287
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003288SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3289 return mSystemCameraKind;
3290}
3291
Shuzhen Wang43858162020-01-10 13:42:15 -08003292bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3293 Mutex::Autolock lock(mStatusLock);
3294 auto result = mUnavailablePhysicalIds.insert(physicalId);
3295 return result.second;
3296}
3297
3298bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3299 Mutex::Autolock lock(mStatusLock);
3300 auto count = mUnavailablePhysicalIds.erase(physicalId);
3301 return count > 0;
3302}
3303
Ruben Brunkcc776712015-02-17 20:18:47 -08003304// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003305// ClientEventListener
3306// ----------------------------------------------------------------------------
3307
3308void CameraService::ClientEventListener::onClientAdded(
3309 const resource_policy::ClientDescriptor<String8,
3310 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003311 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003312 if (basicClient.get() != nullptr) {
3313 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3314 notifier.noteStartCamera(descriptor.getKey(),
3315 static_cast<int>(basicClient->getClientUid()));
3316 }
3317}
3318
3319void CameraService::ClientEventListener::onClientRemoved(
3320 const resource_policy::ClientDescriptor<String8,
3321 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003322 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003323 if (basicClient.get() != nullptr) {
3324 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3325 notifier.noteStopCamera(descriptor.getKey(),
3326 static_cast<int>(basicClient->getClientUid()));
3327 }
3328}
3329
3330
3331// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003332// CameraClientManager
3333// ----------------------------------------------------------------------------
3334
Ruben Brunk99e69712015-05-26 17:25:07 -07003335CameraService::CameraClientManager::CameraClientManager() {
3336 setListener(std::make_shared<ClientEventListener>());
3337}
3338
Ruben Brunkcc776712015-02-17 20:18:47 -08003339CameraService::CameraClientManager::~CameraClientManager() {}
3340
3341sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3342 const String8& id) const {
3343 auto descriptor = get(id);
3344 if (descriptor == nullptr) {
3345 return sp<BasicClient>{nullptr};
3346 }
3347 return descriptor->getValue();
3348}
3349
3350String8 CameraService::CameraClientManager::toString() const {
3351 auto all = getAll();
3352 String8 ret("[");
3353 bool hasAny = false;
3354 for (auto& i : all) {
3355 hasAny = true;
3356 String8 key = i->getKey();
3357 int32_t cost = i->getCost();
3358 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003359 int32_t score = i->getPriority().getScore();
3360 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003361 auto conflicting = i->getConflicting();
3362 auto clientSp = i->getValue();
3363 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003364 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003365 if (clientSp.get() != nullptr) {
3366 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003367 uid_t clientUid = clientSp->getClientUid();
3368 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003369 }
Emilian Peev8131a262017-02-01 12:33:43 +00003370 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3371 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003372
Ruben Brunk6267b532015-04-30 17:44:07 -07003373 if (clientSp.get() != nullptr) {
3374 ret.appendFormat("User Id: %d, ", clientUserId);
3375 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003376 if (packageName.size() != 0) {
3377 ret.appendFormat("Client Package Name: %s", packageName.string());
3378 }
3379
3380 ret.append(", Conflicting Client Devices: {");
3381 for (auto& j : conflicting) {
3382 ret.appendFormat("%s, ", j.string());
3383 }
3384 ret.append("})");
3385 }
3386 if (hasAny) ret.append("\n");
3387 ret.append("]\n");
3388 return ret;
3389}
3390
3391CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3392 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003393 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3394 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003395
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003396 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003397 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3398 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3399
Ruben Brunkcc776712015-02-17 20:18:47 -08003400 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003401 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003402}
3403
3404CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3405 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3406 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003407 partial->getConflicting(), partial->getPriority().getScore(),
3408 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003409}
3410
3411// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412
3413static const int kDumpLockRetries = 50;
3414static const int kDumpLockSleep = 60000;
3415
3416static bool tryLock(Mutex& mutex)
3417{
3418 bool locked = false;
3419 for (int i = 0; i < kDumpLockRetries; ++i) {
3420 if (mutex.tryLock() == NO_ERROR) {
3421 locked = true;
3422 break;
3423 }
3424 usleep(kDumpLockSleep);
3425 }
3426 return locked;
3427}
3428
3429status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003430 ATRACE_CALL();
3431
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003432 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003433 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003434 CameraThreadState::getCallingPid(),
3435 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003436 return NO_ERROR;
3437 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003438 bool locked = tryLock(mServiceLock);
3439 // failed to lock - CameraService is probably deadlocked
3440 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003441 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003442 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003443
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003444 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003445 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003446
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003447 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003448 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003449
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003450 if (locked) mServiceLock.unlock();
3451 return NO_ERROR;
3452 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003453 dprintf(fd, "\n== Service global info: ==\n\n");
3454 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003455 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003456 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3457 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003458 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3459 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3460 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003461 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003462 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3463 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003464
3465 dumpEventLog(fd);
3466
3467 bool stateLocked = tryLock(mCameraStatesLock);
3468 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003469 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003470 }
3471
Emilian Peevbd8c5032018-02-14 23:05:40 +00003472 int argSize = args.size();
3473 for (int i = 0; i < argSize; i++) {
3474 if (args[i] == TagMonitor::kMonitorOption) {
3475 if (i + 1 < argSize) {
3476 mMonitorTags = String8(args[i + 1]);
3477 }
3478 break;
3479 }
3480 }
3481
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003482 for (auto& state : mCameraStates) {
3483 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003484
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003485 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003486
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003487 CameraParameters p = state.second->getShimParams();
3488 if (!p.isEmpty()) {
3489 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3490 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003491 }
3492
3493 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003494 if (clientDescriptor != nullptr) {
3495 dprintf(fd, " Device %s is open. Client instance dump:\n",
3496 cameraId.string());
3497 dprintf(fd, " Client priority score: %d state: %d\n",
3498 clientDescriptor->getPriority().getScore(),
3499 clientDescriptor->getPriority().getState());
3500 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3501
3502 auto client = clientDescriptor->getValue();
3503 dprintf(fd, " Client package: %s\n",
3504 String8(client->getPackageName()).string());
3505
3506 client->dumpClient(fd, args);
3507 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003508 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003509 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003510 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003511
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003512 }
3513
3514 if (stateLocked) mCameraStatesLock.unlock();
3515
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003516 if (locked) mServiceLock.unlock();
3517
Emilian Peevf53f66e2017-04-11 14:29:43 +01003518 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003519
3520 dprintf(fd, "\n== Vendor tags: ==\n\n");
3521
3522 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3523 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003524 sp<VendorTagDescriptorCache> cache =
3525 VendorTagDescriptorCache::getGlobalVendorTagCache();
3526 if (cache == NULL) {
3527 dprintf(fd, "No vendor tags.\n");
3528 } else {
3529 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3530 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003531 } else {
3532 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3533 }
3534
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003535 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003536 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003537 camera3::CameraTraces::dump(fd, args);
3538
3539 // Process dump arguments, if any
3540 int n = args.size();
3541 String16 verboseOption("-v");
3542 String16 unreachableOption("--unreachable");
3543 for (int i = 0; i < n; i++) {
3544 if (args[i] == verboseOption) {
3545 // change logging level
3546 if (i + 1 >= n) continue;
3547 String8 levelStr(args[i+1]);
3548 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003549 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003550 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003551 } else if (args[i] == unreachableOption) {
3552 // Dump memory analysis
3553 // TODO - should limit be an argument parameter?
3554 UnreachableMemoryInfo info;
3555 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3556 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003557 dprintf(fd, "\n== Unable to dump unreachable memory. "
3558 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003559 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003560 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003561 std::string s = info.ToString(/*log_contents*/ true);
3562 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003563 }
3564 }
3565 }
3566 return NO_ERROR;
3567}
3568
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003569void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003570 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003571
3572 Mutex::Autolock l(mLogLock);
3573 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003574 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003575 }
3576
3577 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003578 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003579 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003580 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003581 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003582 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003583}
3584
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003585void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003586 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003587 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3588 if (mTorchClientMap[i] == who) {
3589 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003590 String8 cameraId = mTorchClientMap.keyAt(i);
3591 status_t res = mFlashlight->setTorchMode(cameraId, false);
3592 if (res) {
3593 ALOGE("%s: torch client died but couldn't turn off torch: "
3594 "%s (%d)", __FUNCTION__, strerror(-res), res);
3595 return;
3596 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003597 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003598 break;
3599 }
3600 }
3601}
3602
Ruben Brunkcc776712015-02-17 20:18:47 -08003603/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003604
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003605 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003606 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3607 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003608 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003609 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003610 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003611
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003612 // check torch client
3613 handleTorchClientBinderDied(who);
3614
3615 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003616 if(!evictClientIdByRemote(who)) {
3617 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003618 return;
3619 }
3620
Ruben Brunkcc776712015-02-17 20:18:47 -08003621 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3622 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003623}
3624
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003625void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003626 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003627}
3628
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003629void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3630 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003631 // Do not lock mServiceLock here or can get into a deadlock from
3632 // connect() -> disconnect -> updateStatus
3633
3634 auto state = getCameraState(cameraId);
3635
3636 if (state == nullptr) {
3637 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3638 cameraId.string());
3639 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003640 }
3641
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003642 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3643 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3644 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3645 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3646 return;
3647 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003648 bool supportsHAL3 = false;
3649 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3650 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3651 // mInterfaceMutex together, which can lead to deadlocks)
3652 binder::Status sRet =
3653 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3654 &supportsHAL3);
3655 if (!sRet.isOk()) {
3656 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3657 __FUNCTION__, cameraId.string());
3658 return;
3659 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003660
3661 // Collect the logical cameras without holding mStatusLock in updateStatus
3662 // as that can lead to a deadlock(b/162192331).
3663 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003664 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003665 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003666 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3,
3667 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003668 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003669
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003670 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003671 // Update torch status if it has a flash unit.
3672 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003673 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003674 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3675 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003676 TorchModeStatus newTorchStatus =
3677 status == StatusInternal::PRESENT ?
3678 TorchModeStatus::AVAILABLE_OFF :
3679 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003680 if (torchStatus != newTorchStatus) {
3681 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3682 }
3683 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003684 }
3685
3686 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003687 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
3688 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003689
Ruben Brunkcc776712015-02-17 20:18:47 -08003690 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003691 bool isVendorListener = listener->isVendorListener();
3692 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3693 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003694 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003695 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003696 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003697 continue;
3698 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003699 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003700 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003701 }
3702 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003703}
3704
Shuzhen Wang695044d2020-03-06 09:02:23 -08003705void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3706 const String16& clientPackageName) {
3707 Mutex::Autolock lock(mStatusListenerLock);
3708
3709 for (const auto& it : mListenerList) {
3710 if (!it->isOpenCloseCallbackAllowed()) {
3711 continue;
3712 }
3713
3714 binder::Status ret;
3715 String16 cameraId64(cameraId);
3716 if (open) {
3717 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3718 } else {
3719 ret = it->getListener()->onCameraClosed(cameraId64);
3720 }
3721 if (!ret.isOk()) {
3722 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3723 ret.exceptionCode());
3724 }
3725 }
3726}
3727
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003728template<class Func>
3729void CameraService::CameraState::updateStatus(StatusInternal status,
3730 const String8& cameraId,
3731 std::initializer_list<StatusInternal> rejectSourceStates,
3732 Func onStatusUpdatedLocked) {
3733 Mutex::Autolock lock(mStatusLock);
3734 StatusInternal oldStatus = mStatus;
3735 mStatus = status;
3736
3737 if (oldStatus == status) {
3738 return;
3739 }
3740
3741 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3742 cameraId.string(), oldStatus, status);
3743
3744 if (oldStatus == StatusInternal::NOT_PRESENT &&
3745 (status != StatusInternal::PRESENT &&
3746 status != StatusInternal::ENUMERATING)) {
3747
3748 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3749 __FUNCTION__);
3750 mStatus = oldStatus;
3751 return;
3752 }
3753
3754 /**
3755 * Sometimes we want to conditionally do a transition.
3756 * For example if a client disconnects, we want to go to PRESENT
3757 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3758 */
3759 for (auto& rejectStatus : rejectSourceStates) {
3760 if (oldStatus == rejectStatus) {
3761 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3762 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3763 mStatus = oldStatus;
3764 return;
3765 }
3766 }
3767
3768 onStatusUpdatedLocked(cameraId, status);
3769}
3770
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003771status_t CameraService::getTorchStatusLocked(
3772 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003773 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003774 if (!status) {
3775 return BAD_VALUE;
3776 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003777 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3778 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003779 // invalid camera ID or the camera doesn't have a flash unit
3780 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003781 }
3782
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003783 *status = mTorchStatusMap.valueAt(index);
3784 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003785}
3786
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003787status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003788 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003789 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3790 if (index == NAME_NOT_FOUND) {
3791 return BAD_VALUE;
3792 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003793 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003794
3795 return OK;
3796}
3797
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003798std::list<String16> CameraService::getLogicalCameras(
3799 const String8& physicalCameraId) {
3800 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08003801 Mutex::Autolock lock(mCameraStatesLock);
3802 for (const auto& state : mCameraStates) {
3803 std::vector<std::string> physicalCameraIds;
3804 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3805 // This is not a logical multi-camera.
3806 continue;
3807 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003808 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08003809 == physicalCameraIds.end()) {
3810 // cameraId is not a physical camera of this logical multi-camera.
3811 continue;
3812 }
3813
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003814 retList.emplace_back(String16(state.first));
3815 }
3816 return retList;
3817}
3818
3819void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
3820 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
3821 SystemCameraKind deviceKind) {
3822 // mStatusListenerLock is expected to be locked
3823 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003824 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003825 // Note: we check only the deviceKind of the physical camera id
3826 // since, logical camera ids and their physical camera ids are
3827 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003828 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3829 listener->getListenerPid(), listener->getListenerUid())) {
3830 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003831 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003832 continue;
3833 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003834 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003835 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08003836 }
3837 }
3838}
3839
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00003840
Svet Ganova453d0d2018-01-11 15:37:58 -08003841void CameraService::blockClientsForUid(uid_t uid) {
3842 const auto clients = mActiveClientManager.getAll();
3843 for (auto& current : clients) {
3844 if (current != nullptr) {
3845 const auto basicClient = current->getValue();
3846 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3847 basicClient->block();
3848 }
3849 }
3850 }
3851}
3852
Michael Grooverd1d435a2018-12-18 17:39:42 -08003853void CameraService::blockAllClients() {
3854 const auto clients = mActiveClientManager.getAll();
3855 for (auto& current : clients) {
3856 if (current != nullptr) {
3857 const auto basicClient = current->getValue();
3858 if (basicClient.get() != nullptr) {
3859 basicClient->block();
3860 }
3861 }
3862 }
3863}
3864
Svet Ganova453d0d2018-01-11 15:37:58 -08003865// NOTE: This is a remote API - make sure all args are validated
3866status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3867 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3868 return PERMISSION_DENIED;
3869 }
3870 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3871 return BAD_VALUE;
3872 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003873 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003874 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003875 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003876 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003877 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003878 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003879 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3880 return handleSetRotateAndCrop(args);
3881 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3882 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003883 } else if (args.size() == 1 && args[0] == String16("help")) {
3884 printHelp(out);
3885 return NO_ERROR;
3886 }
3887 printHelp(err);
3888 return BAD_VALUE;
3889}
3890
3891status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003892 String16 packageName = args[1];
3893
Svet Ganova453d0d2018-01-11 15:37:58 -08003894 bool active = false;
3895 if (args[2] == String16("active")) {
3896 active = true;
3897 } else if ((args[2] != String16("idle"))) {
3898 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3899 return BAD_VALUE;
3900 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003901
3902 int userId = 0;
3903 if (args.size() >= 5 && args[3] == String16("--user")) {
3904 userId = atoi(String8(args[4]));
3905 }
3906
3907 uid_t uid;
3908 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3909 return BAD_VALUE;
3910 }
3911
3912 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003913 return NO_ERROR;
3914}
3915
3916status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003917 String16 packageName = args[1];
3918
3919 int userId = 0;
3920 if (args.size() >= 4 && args[2] == String16("--user")) {
3921 userId = atoi(String8(args[3]));
3922 }
3923
3924 uid_t uid;
3925 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003926 return BAD_VALUE;
3927 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003928
3929 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003930 return NO_ERROR;
3931}
3932
3933status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003934 String16 packageName = args[1];
3935
3936 int userId = 0;
3937 if (args.size() >= 4 && args[2] == String16("--user")) {
3938 userId = atoi(String8(args[3]));
3939 }
3940
3941 uid_t uid;
3942 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003943 return BAD_VALUE;
3944 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003945
3946 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003947 return dprintf(out, "active\n");
3948 } else {
3949 return dprintf(out, "idle\n");
3950 }
3951}
3952
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003953status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
3954 int rotateValue = atoi(String8(args[1]));
3955 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
3956 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
3957 Mutex::Autolock lock(mServiceLock);
3958
3959 mOverrideRotateAndCropMode = rotateValue;
3960
3961 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
3962
3963 const auto clients = mActiveClientManager.getAll();
3964 for (auto& current : clients) {
3965 if (current != nullptr) {
3966 const auto basicClient = current->getValue();
3967 if (basicClient.get() != nullptr) {
3968 basicClient->setRotateAndCropOverride(rotateValue);
3969 }
3970 }
3971 }
3972
3973 return OK;
3974}
3975
3976status_t CameraService::handleGetRotateAndCrop(int out) {
3977 Mutex::Autolock lock(mServiceLock);
3978
3979 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
3980}
3981
Svet Ganova453d0d2018-01-11 15:37:58 -08003982status_t CameraService::printHelp(int out) {
3983 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07003984 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3985 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3986 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003987 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
3988 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
3989 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08003990 " help print this message\n");
3991}
3992
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003993int32_t CameraService::updateAudioRestriction() {
3994 Mutex::Autolock lock(mServiceLock);
3995 return updateAudioRestrictionLocked();
3996}
3997
3998int32_t CameraService::updateAudioRestrictionLocked() {
3999 int32_t mode = 0;
4000 // iterate through all active client
4001 for (const auto& i : mActiveClientManager.getAll()) {
4002 const auto clientSp = i->getValue();
4003 mode |= clientSp->getAudioRestriction();
4004 }
4005
4006 bool modeChanged = (mAudioRestriction != mode);
4007 mAudioRestriction = mode;
4008 if (modeChanged) {
4009 mAppOps.setCameraAudioRestriction(mode);
4010 }
4011 return mode;
4012}
4013
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014}; // namespace android