blob: 9af1c36147e234a05f406d79c99ae1c0f8d9483e [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080024#include <cstring>
25#include <ctime>
26#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080028#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <pthread.h>
30
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080031#include <android/hardware/ICamera.h>
32#include <android/hardware/ICameraClient.h>
33
Alex Deymo9c2a2c22016-08-25 11:59:14 -070034#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080035#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070036#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080037#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080038#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
41#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <binder/ProcessInfoService.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080046#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070048#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080050#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070052#include "hidl/HidlCameraService.h"
53#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080054#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070055#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080057#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070059#include <mediautils/BatteryNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/CameraClient.h"
74#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070076#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000077#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070078#include "utils/CameraThreadState.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070088using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080089using hardware::ICamera;
90using hardware::ICameraClient;
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -070091using hardware::ICameraServiceProxy;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080092using hardware::ICameraServiceListener;
93using hardware::camera::common::V1_0::CameraDeviceStatus;
94using hardware::camera::common::V1_0::TorchModeStatus;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080095using hardware::camera2::utils::CameraIdAndSessionConfiguration;
96using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080097
Mathias Agopian65ab4712010-07-14 17:59:35 -070098// ----------------------------------------------------------------------------
99// Logging support -- this is for debugging only
100// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700101volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
Steve Blockb8a80522011-12-20 16:23:08 +0000103#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
104#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
106static void setLogLevel(int level) {
107 android_atomic_write(level, &gLogLevel);
108}
109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800110// Convenience methods for constructing binder::Status objects for error returns
111
112#define STATUS_ERROR(errorCode, errorString) \
113 binder::Status::fromServiceSpecificError(errorCode, \
114 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
115
116#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
117 binder::Status::fromServiceSpecificError(errorCode, \
118 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
119 __VA_ARGS__))
120
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121// ----------------------------------------------------------------------------
122
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700123static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800124static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700125static const String16 sCameraPermission("android.permission.CAMERA");
126static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
127static const String16
128 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800129static const String16 sCameraOpenCloseListenerPermission(
130 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Svet Ganova453d0d2018-01-11 15:37:58 -0800131
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700132// Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
133static constexpr int32_t kVendorClientScore = 200;
134// Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
135static constexpr int32_t kVendorClientState = 1;
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800136const String8 CameraService::kOfflineDevice("offline-");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700137
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700138Mutex CameraService::sProxyMutex;
139sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
140
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800141CameraService::CameraService() :
142 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800143 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700144 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700145 mSoundRef(0), mInitialized(false),
146 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000147 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800148 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149}
150
Iliyan Malchev8951a972011-04-14 16:55:59 -0700151void CameraService::onFirstRef()
152{
Ruben Brunkcc776712015-02-17 20:18:47 -0800153 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800154
Iliyan Malchev8951a972011-04-14 16:55:59 -0700155 BnCameraService::onFirstRef();
156
Ruben Brunk99e69712015-05-26 17:25:07 -0700157 // Update battery life tracking if service is restarting
158 BatteryNotifier& notifier(BatteryNotifier::getInstance());
159 notifier.noteResetCamera();
160 notifier.noteResetFlashlight();
161
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800162 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800163
Emilian Peevf53f66e2017-04-11 14:29:43 +0100164 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800165 if (res == OK) {
166 mInitialized = true;
167 }
168
Svet Ganova453d0d2018-01-11 15:37:58 -0800169 mUidPolicy = new UidPolicy(this);
170 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800171 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
172 mSensorPrivacyPolicy->registerSelf();
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700173 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700174 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
175 if (hcs->registerAsService() != android::OK) {
176 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
177 __FUNCTION__);
178 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700179
180 // This needs to be last call in this function, so that it's as close to
181 // ServiceManager::addService() as possible.
182 CameraService::pingCameraServiceProxy();
183 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800184}
185
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800186status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800187 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100188
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800189 std::vector<std::string> deviceIds;
190 {
191 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800192
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800193 if (nullptr == mCameraProviderManager.get()) {
194 mCameraProviderManager = new CameraProviderManager();
195 res = mCameraProviderManager->initialize(this);
196 if (res != OK) {
197 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
198 __FUNCTION__, strerror(-res), res);
199 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100200 }
201 }
202
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800203
204 // Setup vendor tags before we call get_camera_info the first time
205 // because HAL might need to setup static vendor keys in get_camera_info
206 // TODO: maybe put this into CameraProviderManager::initialize()?
207 mCameraProviderManager->setUpVendorTags();
208
209 if (nullptr == mFlashlight.get()) {
210 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700211 }
212
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800213 res = mFlashlight->findFlashUnits();
214 if (res != OK) {
215 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
216 }
217
218 deviceIds = mCameraProviderManager->getCameraDeviceIds();
219 }
220
221
222 for (auto& cameraId : deviceIds) {
223 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800224 if (getCameraState(id8) == nullptr) {
225 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
226 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800227 }
228
229 return OK;
230}
231
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700232sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800233#ifndef __BRILLO__
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700234 Mutex::Autolock al(sProxyMutex);
235 if (sCameraServiceProxy == nullptr) {
236 sp<IServiceManager> sm = defaultServiceManager();
237 // Use checkService because cameraserver normally starts before the
238 // system server and the proxy service. So the long timeout that getService
239 // has before giving up is inappropriate.
240 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
241 if (binder != nullptr) {
242 sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
243 }
Ruben Brunk2823ce02015-05-19 17:25:13 -0700244 }
Christopher Wiley92c06fc2016-02-11 15:40:05 -0800245#endif
Eino-Ville Talvala7d5569f2019-04-08 13:57:54 -0700246 return sCameraServiceProxy;
Eino-Ville Talvala412fe562015-08-20 17:08:32 -0700247}
248
249void CameraService::pingCameraServiceProxy() {
250 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
251 if (proxyBinder == nullptr) return;
Ruben Brunk2823ce02015-05-19 17:25:13 -0700252 proxyBinder->pingForUserUpdate();
Iliyan Malchev8951a972011-04-14 16:55:59 -0700253}
254
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800255void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
256 Mutex::Autolock lock(mStatusListenerLock);
257
258 for (auto& i : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700259 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800260 }
261}
262
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800264 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800265 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800266 mSensorPrivacyPolicy->unregisterSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267}
268
Emilian Peevaee727d2017-05-04 16:35:48 +0100269void CameraService::onNewProviderRegistered() {
270 enumerateProviders();
271}
272
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700273void CameraService::filterAPI1SystemCameraLocked(
274 const std::vector<std::string> &normalDeviceIds) {
275 mNormalDeviceIdsWithoutSystemCamera.clear();
276 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700277 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
278 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
279 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
280 continue;
281 }
282 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700283 // All system camera ids will necessarily come after public camera
284 // device ids as per the HAL interface contract.
285 break;
286 }
287 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
288 }
289 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
290 mNormalDeviceIdsWithoutSystemCamera.size());
291}
292
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700293status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
294 auto state = getCameraState(cameraId);
295 if (state != nullptr) {
296 *kind = state->getSystemCameraKind();
297 return OK;
298 }
299 // Hidden physical camera ids won't have CameraState
300 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
301}
302
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800303void CameraService::updateCameraNumAndIds() {
304 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700305 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
306 // Excludes hidden secure cameras
307 mNumberOfCameras =
308 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
309 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800310 mNormalDeviceIds =
311 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700312 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800313}
314
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100315void CameraService::addStates(const String8 id) {
316 std::string cameraId(id.c_str());
317 hardware::camera::common::V1_0::CameraResourceCost cost;
318 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700319 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100320 if (res != OK) {
321 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
322 return;
323 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700324 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
325 if (res != OK) {
326 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
327 return;
328 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100329 std::set<String8> conflicting;
330 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
331 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
332 }
333
334 {
335 Mutex::Autolock lock(mCameraStatesLock);
336 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700337 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100338 }
339
340 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100341 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100342 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800343
344 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100345 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800346
347 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100348 logDeviceAdded(id, "Device added");
349}
350
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100351void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800352 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100353 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100354 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100355 mTorchStatusMap.removeItem(id);
356 }
357
358 {
359 Mutex::Autolock lock(mCameraStatesLock);
360 mCameraStates.erase(id);
361 }
362}
363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800364void CameraService::onDeviceStatusChanged(const String8& id,
365 CameraDeviceStatus newHalStatus) {
366 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
367 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700368
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800369 StatusInternal newStatus = mapToInternal(newHalStatus);
370
Ruben Brunkcc776712015-02-17 20:18:47 -0800371 std::shared_ptr<CameraState> state = getCameraState(id);
372
373 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700374 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100375 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700376 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100377
378 // First add as absent to make sure clients are notified below
379 addStates(id);
380
381 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700382 } else {
383 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
384 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700385 return;
386 }
387
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800388 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800389
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800390 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800391 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700392 return;
393 }
394
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800395 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700396 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
397 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800398
399 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
400 // to this device until the status changes
401 updateStatus(StatusInternal::NOT_PRESENT, id);
402
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800403 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700404 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800405 // Don't do this in updateStatus to avoid deadlock over mServiceLock
406 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700407
Ruben Brunkcc776712015-02-17 20:18:47 -0800408 // Remove cached shim parameters
409 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700410
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800411 // Remove online as well as offline client from the list of active clients,
412 // if they are present
413 clientToDisconnectOnline = removeClientLocked(id);
414 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700415 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800416
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800417 disconnectClient(id, clientToDisconnectOnline);
418 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700419
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100420 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800421 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800422 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700423 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
424 newStatus));
425 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800426 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700427 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800428}
Igor Murashkincba2c162013-03-20 15:56:31 -0700429
Shuzhen Wang43858162020-01-10 13:42:15 -0800430void CameraService::onDeviceStatusChanged(const String8& id,
431 const String8& physicalId,
432 CameraDeviceStatus newHalStatus) {
433 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
434 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
435
436 StatusInternal newStatus = mapToInternal(newHalStatus);
437
438 std::shared_ptr<CameraState> state = getCameraState(id);
439
440 if (state == nullptr) {
441 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
442 __FUNCTION__, id.string(), physicalId.string());
443 return;
444 }
445
446 StatusInternal logicalCameraStatus = state->getStatus();
447 if (logicalCameraStatus != StatusInternal::PRESENT &&
448 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
449 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
450 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
451 return;
452 }
453
454 bool updated = false;
455 if (newStatus == StatusInternal::PRESENT) {
456 updated = state->removeUnavailablePhysicalId(physicalId);
457 } else {
458 updated = state->addUnavailablePhysicalId(physicalId);
459 }
460
461 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800462 String8 idCombo = id + " : " + physicalId;
463 if (newStatus == StatusInternal::PRESENT) {
464 logDeviceAdded(idCombo,
465 String8::format("Device status changed to %d", newStatus));
466 } else {
467 logDeviceRemoved(idCombo,
468 String8::format("Device status changed to %d", newStatus));
469 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800470
471 String16 id16(id), physicalId16(physicalId);
472 Mutex::Autolock lock(mStatusListenerLock);
473 for (auto& listener : mListenerList) {
474 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
475 id16, physicalId16);
476 }
477 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700478}
479
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800480void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
481 if (clientToDisconnect.get() != nullptr) {
482 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
483 __FUNCTION__, id.string());
484 // Notify the client of disconnection
485 clientToDisconnect->notifyError(
486 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
487 CaptureResultExtras{});
488 // Ensure not in binder RPC so client disconnect PID checks work correctly
489 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
490 "onDeviceStatusChanged must be called from the camera service process!");
491 clientToDisconnect->disconnect();
492 }
493}
494
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800495void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800496 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800497 Mutex::Autolock al(mTorchStatusMutex);
498 onTorchStatusChangedLocked(cameraId, newStatus);
499}
500
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800501void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800502 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800503 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
504 __FUNCTION__, cameraId.string(), newStatus);
505
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800506 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800507 status_t res = getTorchStatusLocked(cameraId, &status);
508 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700509 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
510 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800511 return;
512 }
513 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800514 return;
515 }
516
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800517 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800518 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800519 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
520 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800521 return;
522 }
523
Ruben Brunkcc776712015-02-17 20:18:47 -0800524 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700525 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700526 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700527 auto iter = mTorchUidMap.find(cameraId);
528 if (iter != mTorchUidMap.end()) {
529 int oldUid = iter->second.second;
530 int newUid = iter->second.first;
531 BatteryNotifier& notifier(BatteryNotifier::getInstance());
532 if (oldUid != newUid) {
533 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700535 notifier.noteFlashlightOff(cameraId, oldUid);
536 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700538 notifier.noteFlashlightOn(cameraId, newUid);
539 }
540 iter->second.second = newUid;
541 } else {
542 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800543 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700544 notifier.noteFlashlightOn(cameraId, oldUid);
545 } else {
546 notifier.noteFlashlightOff(cameraId, oldUid);
547 }
548 }
549 }
550 }
551
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800552 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800553}
554
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700555static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
556 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
557 checkPermission(sCameraPermission, callingPid, callingUid);
558}
559
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800560Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700561 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100562 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700563 bool hasSystemCameraPermissions =
564 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
565 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700566 switch (type) {
567 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700568 if (hasSystemCameraPermissions) {
569 *numCameras = static_cast<int>(mNormalDeviceIds.size());
570 } else {
571 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
572 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800573 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700574 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700575 if (hasSystemCameraPermissions) {
576 *numCameras = mNumberOfCameras;
577 } else {
578 *numCameras = mNumberOfCamerasWithoutSystemCamera;
579 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800580 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700581 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800582 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700583 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
585 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700586 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800587 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588}
589
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800590Status CameraService::getCameraInfo(int cameraId,
591 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700592 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100593 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700594 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
595 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
596 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
597 "characteristics for system only device %s: ", cameraIdStr.c_str());
598 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100599
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800600 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601 return STATUS_ERROR(ERROR_DISCONNECTED,
602 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700603 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700604 bool hasSystemCameraPermissions =
605 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
606 CameraThreadState::getCallingUid());
607 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
608 if (hasSystemCameraPermissions) {
609 cameraIdBound = mNumberOfCameras;
610 }
611 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800612 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
613 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 }
615
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800616 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800617 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700618 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100619 if (err != OK) {
620 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
621 "Error retrieving camera info from device %d: %s (%d)", cameraId,
622 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800623 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100624
Ruben Brunkcc776712015-02-17 20:18:47 -0800625 return ret;
626}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700627
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800628std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700629 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
630 auto callingPid = CameraThreadState::getCallingPid();
631 auto callingUid = CameraThreadState::getCallingUid();
632 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
633 getpid() == callingPid) {
634 deviceIds = &mNormalDeviceIds;
635 }
636 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800637 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700638 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800639 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800640 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800641
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700642 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800643}
644
645String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
646 Mutex::Autolock lock(mServiceLock);
647 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800648}
649
650Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800651 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700652 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700653 if (!cameraInfo) {
654 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800655 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700656 }
657
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800658 if (!mInitialized) {
659 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800660 return STATUS_ERROR(ERROR_DISCONNECTED,
661 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700662 }
663
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700664 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
665 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
666 "characteristics for system only device %s: ", String8(cameraId).string());
667 }
668
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800669 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800670
Emilian Peevf53f66e2017-04-11 14:29:43 +0100671 status_t res = mCameraProviderManager->getCameraCharacteristics(
672 String8(cameraId).string(), cameraInfo);
673 if (res != OK) {
674 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
675 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
676 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700677 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700678 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
679 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
680 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
681 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
682 "for device %s", String8(cameraId).string());
683 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700684 int callingPid = CameraThreadState::getCallingPid();
685 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100686 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700687 // If it's not calling from cameraserver, check the permission only if
688 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
689 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100690 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700691 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700692 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100693 res = cameraInfo->removePermissionEntries(
694 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
695 &tagsRemoved);
696 if (res != OK) {
697 cameraInfo->clear();
698 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
699 " characteristics needing camera permission for device %s: %s (%d)",
700 String8(cameraId).string(), strerror(-res), res);
701 }
702 }
703
704 if (!tagsRemoved.empty()) {
705 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
706 tagsRemoved.data(), tagsRemoved.size());
707 if (res != OK) {
708 cameraInfo->clear();
709 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
710 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
711 strerror(-res), res);
712 }
713 }
714
Zhijun He2b59be82013-09-25 10:14:30 -0700715 return ret;
716}
717
Ruben Brunkcc776712015-02-17 20:18:47 -0800718String8 CameraService::getFormattedCurrentTime() {
719 time_t now = time(nullptr);
720 char formattedTime[64];
721 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
722 return String8(formattedTime);
723}
724
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800725Status CameraService::getCameraVendorTagDescriptor(
726 /*out*/
727 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700728 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800729 if (!mInitialized) {
730 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800731 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800732 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800733 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
734 if (globalDescriptor != nullptr) {
735 *desc = *(globalDescriptor.get());
736 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800737 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800738}
739
Emilian Peev71c73a22017-03-21 16:35:51 +0000740Status CameraService::getCameraVendorTagCache(
741 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
742 ATRACE_CALL();
743 if (!mInitialized) {
744 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
745 return STATUS_ERROR(ERROR_DISCONNECTED,
746 "Camera subsystem not available");
747 }
748 sp<VendorTagDescriptorCache> globalCache =
749 VendorTagDescriptorCache::getGlobalVendorTagCache();
750 if (globalCache != nullptr) {
751 *cache = *(globalCache.get());
752 }
753 return Status::ok();
754}
755
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800756int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700757 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800758
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800759 int deviceVersion = 0;
760
Emilian Peevf53f66e2017-04-11 14:29:43 +0100761 status_t res;
762 hardware::hidl_version maxVersion{0,0};
763 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
764 &maxVersion);
765 if (res != OK) return -1;
766 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800767
Emilian Peevf53f66e2017-04-11 14:29:43 +0100768 hardware::CameraInfo info;
769 if (facing) {
770 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800771 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100772 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800773 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100774
Igor Murashkin634a5152013-02-20 17:15:11 -0800775 return deviceVersion;
776}
777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800778Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700779 switch(err) {
780 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800781 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800782 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
784 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800785 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800786 return STATUS_ERROR(ERROR_DISCONNECTED,
787 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700788 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
790 "Camera HAL encountered error %d: %s",
791 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700792 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800793}
794
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800795Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800796 const sp<IInterface>& cameraCb, const String16& packageName,
797 const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
798 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
799 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800800 /*out*/sp<BasicClient>* client) {
801
Ruben Brunkcc776712015-02-17 20:18:47 -0800802 if (halVersion < 0 || halVersion == deviceVersion) {
803 // Default path: HAL version is unspecified by caller, create CameraClient
804 // based on device version reported by the HAL.
805 switch(deviceVersion) {
806 case CAMERA_DEVICE_API_VERSION_1_0:
807 if (effectiveApiLevel == API_1) { // Camera1 API route
808 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800809 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800810 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700811 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800812 } else { // Camera2 API route
813 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800815 "Camera device \"%s\" HAL version %d does not support camera2 API",
816 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800817 }
818 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800819 case CAMERA_DEVICE_API_VERSION_3_0:
820 case CAMERA_DEVICE_API_VERSION_3_1:
821 case CAMERA_DEVICE_API_VERSION_3_2:
822 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700823 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700824 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800825 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800826 if (effectiveApiLevel == API_1) { // Camera1 API route
827 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800828 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800829 cameraId, api1CameraId,
830 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700831 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
834 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800835 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
836 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 }
838 break;
839 default:
840 // Should not be reachable
841 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800842 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800843 "Camera device \"%s\" has unknown HAL version %d",
844 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800845 }
846 } else {
847 // A particular HAL version is requested by caller. Create CameraClient
848 // based on the requested HAL version.
849 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
850 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
851 // Only support higher HAL version device opened as HAL1.0 device.
852 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800853 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800854 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700855 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800856 } else {
857 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
858 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
859 " opened as HAL %x device", halVersion, deviceVersion,
860 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800861 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800862 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
863 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800864 }
865 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800866 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800867}
868
Ruben Brunk6267b532015-04-30 17:44:07 -0700869String8 CameraService::toString(std::set<userid_t> intSet) {
870 String8 s("");
871 bool first = true;
872 for (userid_t i : intSet) {
873 if (first) {
874 s.appendFormat("%d", i);
875 first = false;
876 } else {
877 s.appendFormat(", %d", i);
878 }
879 }
880 return s;
881}
882
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800883int32_t CameraService::mapToInterface(TorchModeStatus status) {
884 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
885 switch (status) {
886 case TorchModeStatus::NOT_AVAILABLE:
887 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
888 break;
889 case TorchModeStatus::AVAILABLE_OFF:
890 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
891 break;
892 case TorchModeStatus::AVAILABLE_ON:
893 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
894 break;
895 default:
896 ALOGW("Unknown new flash status: %d", status);
897 }
898 return serviceStatus;
899}
900
901CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
902 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
903 switch (status) {
904 case CameraDeviceStatus::NOT_PRESENT:
905 serviceStatus = StatusInternal::NOT_PRESENT;
906 break;
907 case CameraDeviceStatus::PRESENT:
908 serviceStatus = StatusInternal::PRESENT;
909 break;
910 case CameraDeviceStatus::ENUMERATING:
911 serviceStatus = StatusInternal::ENUMERATING;
912 break;
913 default:
914 ALOGW("Unknown new HAL device status: %d", status);
915 }
916 return serviceStatus;
917}
918
919int32_t CameraService::mapToInterface(StatusInternal status) {
920 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
921 switch (status) {
922 case StatusInternal::NOT_PRESENT:
923 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
924 break;
925 case StatusInternal::PRESENT:
926 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
927 break;
928 case StatusInternal::ENUMERATING:
929 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
930 break;
931 case StatusInternal::NOT_AVAILABLE:
932 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
933 break;
934 case StatusInternal::UNKNOWN:
935 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
936 break;
937 default:
938 ALOGW("Unknown new internal device status: %d", status);
939 }
940 return serviceStatus;
941}
942
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800943Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700944 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700945
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800946 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800947 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800948 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800950 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800951 sp<ICameraClient>{nullptr}, id, cameraId,
952 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800953 internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700954 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800955 ).isOk()) {
956 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700957 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700959}
960
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800961Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700962 /*out*/
963 CameraParameters* parameters) {
964
965 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
966
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800967 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700968
969 if (parameters == NULL) {
970 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800971 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700972 }
973
Ruben Brunkcc776712015-02-17 20:18:47 -0800974 String8 id = String8::format("%d", cameraId);
975
976 // Check if we already have parameters
977 {
978 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700979 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800980 auto cameraState = getCameraState(id);
981 if (cameraState == nullptr) {
982 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800983 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
984 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800985 }
986 CameraParameters p = cameraState->getShimParams();
987 if (!p.isEmpty()) {
988 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800989 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700990 }
991 }
992
Jayant Chowdhary12361932018-08-27 14:46:13 -0700993 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -0800994 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -0700995 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800996 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800997 // Error already logged by callee
998 return ret;
999 }
1000
1001 // Check for parameters again
1002 {
1003 // Scope for service lock
1004 Mutex::Autolock lock(mServiceLock);
1005 auto cameraState = getCameraState(id);
1006 if (cameraState == nullptr) {
1007 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001008 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1009 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001010 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001011 CameraParameters p = cameraState->getShimParams();
1012 if (!p.isEmpty()) {
1013 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001014 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001015 }
1016 }
1017
Ruben Brunkcc776712015-02-17 20:18:47 -08001018 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1019 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001020 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001021}
1022
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001023// Can camera service trust the caller based on the calling UID?
1024static bool isTrustedCallingUid(uid_t uid) {
1025 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001026 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001027 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001028 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001029 return true;
1030 default:
1031 return false;
1032 }
1033}
1034
Nicholas Sauera3620332019-04-03 14:05:17 -07001035static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1036 PermissionController pc;
1037 uid = pc.getPackageUid(packageName, 0);
1038 if (uid <= 0) {
1039 ALOGE("Unknown package: '%s'", String8(packageName).string());
1040 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1041 return BAD_VALUE;
1042 }
1043
1044 if (userId < 0) {
1045 ALOGE("Invalid user: %d", userId);
1046 dprintf(err, "Invalid user: %d\n", userId);
1047 return BAD_VALUE;
1048 }
1049
1050 uid = multiuser_get_uid(userId, uid);
1051 return NO_ERROR;
1052}
1053
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001054Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001055 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1056 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001057
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001058#ifdef __BRILLO__
1059 UNUSED(clientName8);
1060 UNUSED(clientUid);
1061 UNUSED(clientPid);
1062 UNUSED(originalClientPid);
1063#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001064 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1065 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001066 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001067 return allowed;
1068 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001069#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001070
Jayant Chowdhary12361932018-08-27 14:46:13 -07001071 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001072
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001073 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001074 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1075 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001076 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1077 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001078 }
1079
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 if (getCameraState(cameraId) == nullptr) {
1081 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1082 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001083 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1084 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 }
1086
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001087 status_t err = checkIfDeviceIsUsable(cameraId);
1088 if (err != NO_ERROR) {
1089 switch(err) {
1090 case -ENODEV:
1091 case -EBUSY:
1092 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1093 "No camera device with ID \"%s\" currently available", cameraId.string());
1094 default:
1095 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1096 "Unknown error connecting to ID \"%s\"", cameraId.string());
1097 }
1098 }
1099 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001100}
1101
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001102Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001103 const String8& clientName8, int& clientUid, int& clientPid,
1104 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001105 int callingPid = CameraThreadState::getCallingPid();
1106 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001108 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001110 clientUid = callingUid;
1111 } else if (!isTrustedCallingUid(callingUid)) {
1112 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1113 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001114 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1115 "Untrusted caller (calling PID %d, UID %d) trying to "
1116 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1117 callingPid, callingUid, cameraId.string(),
1118 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 }
1120
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001121 // Check if we can trust clientPid
1122 if (clientPid == USE_CALLING_PID) {
1123 clientPid = callingPid;
1124 } else if (!isTrustedCallingUid(callingUid)) {
1125 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1126 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001127 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1128 "Untrusted caller (calling PID %d, UID %d) trying to "
1129 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1130 callingPid, callingUid, cameraId.string(),
1131 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001132 }
1133
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001134 if (shouldRejectSystemCameraConnection(cameraId)) {
1135 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1136 cameraId.c_str());
1137 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1138 "available", cameraId.string());
1139 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001140 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1141 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1142 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1143 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1144 "found while trying to query device kind", cameraId.string());
1145
1146 }
1147
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001148 // If it's not calling from cameraserver, check the permission if the
1149 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1150 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001151 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001152 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001153 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001154 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001155 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1156 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1157 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001158 }
1159
Svet Ganova453d0d2018-01-11 15:37:58 -08001160 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001161 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001162 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001163 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1164 clientPid, clientUid);
1165 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001166 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1167 "calling UID %d proc state %" PRId32 ")",
1168 clientName8.string(), clientUid, clientPid, cameraId.string(),
1169 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001170 }
1171
Michael Grooverd1d435a2018-12-18 17:39:42 -08001172 // If sensor privacy is enabled then prevent access to the camera
1173 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1174 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1175 return STATUS_ERROR_FMT(ERROR_DISABLED,
1176 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1177 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1178 }
1179
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001180 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1181 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001182 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001183 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184
Ruben Brunk6267b532015-04-30 17:44:07 -07001185 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001186
Ruben Brunka8ca9152015-04-07 14:23:40 -07001187 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001188 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001189 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001190 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001191 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1192 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1193 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001194 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1195 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1196 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001197 }
1198
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001199 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001200}
1201
1202status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1203 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001204 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001205 if (cameraState == nullptr) {
1206 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1207 cameraId.string());
1208 return -ENODEV;
1209 }
1210
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001211 StatusInternal currentStatus = cameraState->getStatus();
1212 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1214 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001215 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001216 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001217 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1218 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001219 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001220 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001221
Ruben Brunkcc776712015-02-17 20:18:47 -08001222 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001223}
1224
Ruben Brunkcc776712015-02-17 20:18:47 -08001225void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1226 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001227
Ruben Brunkcc776712015-02-17 20:18:47 -08001228 // Make a descriptor for the incoming client
1229 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1230 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1231
1232 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1233 String8(client->getPackageName()));
1234
1235 if (evicted.size() > 0) {
1236 // This should never happen - clients should already have been removed in disconnect
1237 for (auto& i : evicted) {
1238 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1239 __FUNCTION__, i->getKey().string());
1240 }
1241
1242 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1243 __FUNCTION__);
1244 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001245
1246 // And register a death notification for the client callback. Do
1247 // this last to avoid Binder policy where a nested Binder
1248 // transaction might be pre-empted to service the client death
1249 // notification if the client process dies before linkToDeath is
1250 // invoked.
1251 sp<IBinder> remoteCallback = client->getRemote();
1252 if (remoteCallback != nullptr) {
1253 remoteCallback->linkToDeath(this);
1254 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001255}
1256
1257status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1258 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1259 /*out*/
1260 sp<BasicClient>* client,
1261 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001262 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001263 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001264 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001265 DescriptorPtr clientDescriptor;
1266 {
1267 if (effectiveApiLevel == API_1) {
1268 // If we are using API1, any existing client for this camera ID with the same remote
1269 // should be returned rather than evicted to allow MediaRecorder to work properly.
1270
1271 auto current = mActiveClientManager.get(cameraId);
1272 if (current != nullptr) {
1273 auto clientSp = current->getValue();
1274 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001275 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1276 ALOGW("CameraService connect called from same client, but with a different"
1277 " API level, evicting prior client...");
1278 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001279 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001280 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 *client = clientSp;
1282 return NO_ERROR;
1283 }
1284 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001285 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001286 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001287
Ruben Brunkcc776712015-02-17 20:18:47 -08001288 // Get current active client PIDs
1289 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1290 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001291
Emilian Peev8131a262017-02-01 12:33:43 +00001292 std::vector<int> priorityScores(ownerPids.size());
1293 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001294
Emilian Peev8131a262017-02-01 12:33:43 +00001295 // Get priority scores of all active PIDs
1296 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1297 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1298 /*out*/&priorityScores[0]);
1299 if (err != OK) {
1300 ALOGE("%s: Priority score query failed: %d",
1301 __FUNCTION__, err);
1302 return err;
1303 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001304
Ruben Brunkcc776712015-02-17 20:18:47 -08001305 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001306 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001307 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001308 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001309 resource_policy::ClientPriority(priorityScores[i], states[i],
1310 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001311 }
1312 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001313
Ruben Brunkcc776712015-02-17 20:18:47 -08001314 // Get state for the given cameraId
1315 auto state = getCameraState(cameraId);
1316 if (state == nullptr) {
1317 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1318 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001319 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001320 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001321 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001322
1323 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001324 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1326 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001327 priorityScores[priorityScores.size() - 1],
1328 clientPid,
1329 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001330
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001331 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1332
Ruben Brunkcc776712015-02-17 20:18:47 -08001333 // Find clients that would be evicted
1334 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1335
1336 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1337 // background, so we cannot do evictions
1338 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1339 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1340 " priority).", clientPid);
1341
1342 sp<BasicClient> clientSp = clientDescriptor->getValue();
1343 String8 curTime = getFormattedCurrentTime();
1344 auto incompatibleClients =
1345 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1346
1347 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001348 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001349 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001350 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001351
1352 for (auto& i : incompatibleClients) {
1353 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001354 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1355 i->getKey().string(),
1356 String8{i->getValue()->getPackageName()}.string(),
1357 i->getOwnerId(), i->getPriority().getScore(),
1358 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001359 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001360 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001361 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001362 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001363 }
1364
1365 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001366 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001367 mEventLog.add(msg);
1368
1369 return -EBUSY;
1370 }
1371
1372 for (auto& i : evicted) {
1373 sp<BasicClient> clientSp = i->getValue();
1374 if (clientSp.get() == nullptr) {
1375 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1376
1377 // TODO: Remove this
1378 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1379 __FUNCTION__);
1380 mActiveClientManager.remove(i);
1381 continue;
1382 }
1383
1384 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1385 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001386 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001387
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001389 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001390 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1391 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001392 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001393 i->getOwnerId(), i->getPriority().getScore(),
1394 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001395 packageName.string(), clientPid, clientPriority.getScore(),
1396 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001397
1398 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001399 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001400 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001401 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001402 }
1403
Ruben Brunkcc776712015-02-17 20:18:47 -08001404 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1405 // other clients from connecting in mServiceLockWrapper if held
1406 mServiceLock.unlock();
1407
1408 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001409 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001410
1411 // Destroy evicted clients
1412 for (auto& i : evictedClients) {
1413 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001414 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001415 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001416
Jayant Chowdhary12361932018-08-27 14:46:13 -07001417 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001418
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001419 for (const auto& i : evictedClients) {
1420 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1421 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1422 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1423 if (ret == TIMED_OUT) {
1424 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1425 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1426 mActiveClientManager.toString().string());
1427 return -EBUSY;
1428 }
1429 if (ret != NO_ERROR) {
1430 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1431 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1432 ret, mActiveClientManager.toString().string());
1433 return ret;
1434 }
1435 }
1436
1437 evictedClients.clear();
1438
Ruben Brunkcc776712015-02-17 20:18:47 -08001439 // Once clients have been disconnected, relock
1440 mServiceLock.lock();
1441
1442 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1443 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1444 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001445 }
1446
Ruben Brunkcc776712015-02-17 20:18:47 -08001447 *partial = clientDescriptor;
1448 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001449}
1450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001451Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001452 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001453 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001454 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001455 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001456 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001457 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001459
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001460 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001462
1463 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001464 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001465 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001466 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
1467 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001468
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001470 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001472 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 }
1474
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001475 *device = client;
1476 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477}
1478
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001479Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001480 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001481 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001482 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001483 int clientUid,
1484 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001485 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001486
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001487 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001488 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001489
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001490 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001491 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001492 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001493 clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
1494 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001495
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001497 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001498 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001499 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001500 }
1501
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001502 *device = client;
1503 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001504}
1505
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001506bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1507 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001508 // If the client is not a vendor client, don't add listener if
1509 // a) the camera is a publicly hidden secure camera OR
1510 // b) the camera is a system only camera and the client doesn't
1511 // have android.permission.SYSTEM_CAMERA permissions.
1512 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1513 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1514 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001515 return true;
1516 }
1517 return false;
1518}
1519
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001520bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1521 // Rules for rejection:
1522 // 1) If cameraserver tries to access this camera device, accept the
1523 // connection.
1524 // 2) The camera device is a publicly hidden secure camera device AND some
1525 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1526 // reject it.
1527 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1528 // and the serving thread is a non hwbinder thread, the client must have
1529 // android.permission.SYSTEM_CAMERA permissions to connect.
1530
1531 int cPid = CameraThreadState::getCallingPid();
1532 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001533 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1534 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1535 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1536 return true;
1537 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001538
1539 // (1) Cameraserver trying to connect, accept.
1540 if (CameraThreadState::getCallingPid() == getpid()) {
1541 return false;
1542 }
1543 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001544 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001545 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1546 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1547 return true;
1548 }
1549 // (3) Here we only check for permissions if it is a system only camera device. This is since
1550 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1551 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1552 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001553 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001554 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1555 !hasPermissionsForSystemCamera(cPid, cUid)) {
1556 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1557 cameraId.c_str());
1558 return true;
1559 }
1560
1561 return false;
1562}
1563
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001564Status CameraService::connectDevice(
1565 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001566 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001567 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001568 const std::unique_ptr<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001569 int clientUid,
1570 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001571 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001572
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001573 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001574 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001575 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001576 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001577 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001578
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001579 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001580 std::string vendorClient =
1581 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1582 clientPackageNameAdj = String16(vendorClient.c_str());
1583 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001585 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001586 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001587 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001588
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001589 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001590 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001591 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001592 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001593 }
1594
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001595 *device = client;
1596 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001597}
1598
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001599template<class CALLBACK, class CLIENT>
1600Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001601 int api1CameraId, int halVersion, const String16& clientPackageName,
1602 const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
1603 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001604 /*out*/sp<CLIENT>& device) {
1605 binder::Status ret = binder::Status::ok();
1606
1607 String8 clientName8(clientPackageName);
1608
1609 int originalClientPid = 0;
1610
1611 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1612 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1613 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1614 static_cast<int>(effectiveApiLevel));
1615
1616 sp<CLIENT> client = nullptr;
1617 {
1618 // Acquire mServiceLock and prevent other clients from connecting
1619 std::unique_ptr<AutoConditionLock> lock =
1620 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1621
1622 if (lock == nullptr) {
1623 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1624 , clientPid);
1625 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1626 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1627 cameraId.string(), clientName8.string(), clientPid);
1628 }
1629
1630 // Enforce client permissions and do basic sanity checks
1631 if(!(ret = validateConnectLocked(cameraId, clientName8,
1632 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1633 return ret;
1634 }
1635
1636 // Check the shim parameters after acquiring lock, if they have already been updated and
1637 // we were doing a shim update, return immediately
1638 if (shimUpdateOnly) {
1639 auto cameraState = getCameraState(cameraId);
1640 if (cameraState != nullptr) {
1641 if (!cameraState->getShimParams().isEmpty()) return ret;
1642 }
1643 }
1644
1645 status_t err;
1646
1647 sp<BasicClient> clientTmp = nullptr;
1648 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1649 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1650 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1651 /*out*/&partial)) != NO_ERROR) {
1652 switch (err) {
1653 case -ENODEV:
1654 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1655 "No camera device with ID \"%s\" currently available",
1656 cameraId.string());
1657 case -EBUSY:
1658 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1659 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1660 cameraId.string());
1661 default:
1662 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1663 "Unexpected error %s (%d) opening camera \"%s\"",
1664 strerror(-err), err, cameraId.string());
1665 }
1666 }
1667
1668 if (clientTmp.get() != nullptr) {
1669 // Handle special case for API1 MediaRecorder where the existing client is returned
1670 device = static_cast<CLIENT*>(clientTmp.get());
1671 return ret;
1672 }
1673
1674 // give flashlight a chance to close devices if necessary.
1675 mFlashlight->prepareDeviceOpen(cameraId);
1676
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001677 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001678 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001679 if (facing == -1) {
1680 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1681 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1682 "Unable to get camera device \"%s\" facing", cameraId.string());
1683 }
1684
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001685 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001686 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001687 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001688 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001689 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001690 /*out*/&tmp)).isOk()) {
1691 return ret;
1692 }
1693 client = static_cast<CLIENT*>(tmp.get());
1694
1695 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1696 __FUNCTION__);
1697
Emilian Peevbd8c5032018-02-14 23:05:40 +00001698 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001699 if (err != OK) {
1700 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001701 // Errors could be from the HAL module open call or from AppOpsManager
1702 switch(err) {
1703 case BAD_VALUE:
1704 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1705 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1706 case -EBUSY:
1707 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1708 "Camera \"%s\" is already open", cameraId.string());
1709 case -EUSERS:
1710 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1711 "Too many cameras already open, cannot open camera \"%s\"",
1712 cameraId.string());
1713 case PERMISSION_DENIED:
1714 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1715 "No permission to open camera \"%s\"", cameraId.string());
1716 case -EACCES:
1717 return STATUS_ERROR_FMT(ERROR_DISABLED,
1718 "Camera \"%s\" disabled by policy", cameraId.string());
1719 case -ENODEV:
1720 default:
1721 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1722 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1723 strerror(-err), err);
1724 }
1725 }
1726
1727 // Update shim paremeters for legacy clients
1728 if (effectiveApiLevel == API_1) {
1729 // Assume we have always received a Client subclass for API1
1730 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1731 String8 rawParams = shimClient->getParameters();
1732 CameraParameters params(rawParams);
1733
1734 auto cameraState = getCameraState(cameraId);
1735 if (cameraState != nullptr) {
1736 cameraState->setShimParams(params);
1737 } else {
1738 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1739 __FUNCTION__, cameraId.string());
1740 }
1741 }
1742
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001743 // Set rotate-and-crop override behavior
1744 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1745 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1746 }
1747
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001748 if (shimUpdateOnly) {
1749 // If only updating legacy shim parameters, immediately disconnect client
1750 mServiceLock.unlock();
1751 client->disconnect();
1752 mServiceLock.lock();
1753 } else {
1754 // Otherwise, add client to active clients list
1755 finishConnectLocked(client, partial);
1756 }
1757 } // lock is destroyed, allow further connect calls
1758
1759 // Important: release the mutex here so the client can call back into the service from its
1760 // destructor (can be at the end of the call)
1761 device = client;
1762 return ret;
1763}
1764
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001765status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1766 if (offlineClient.get() == nullptr) {
1767 return BAD_VALUE;
1768 }
1769
1770 {
1771 // Acquire mServiceLock and prevent other clients from connecting
1772 std::unique_ptr<AutoConditionLock> lock =
1773 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1774
1775 if (lock == nullptr) {
1776 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1777 , __FUNCTION__, offlineClient->getClientPid());
1778 return TIMED_OUT;
1779 }
1780
1781 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1782 if (onlineClientDesc.get() == nullptr) {
1783 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1784 cameraId.c_str());
1785 return BAD_VALUE;
1786 }
1787
1788 // Offline clients do not evict or conflict with other online devices. Resource sharing
1789 // conflicts are handled by the camera provider which will either succeed or fail before
1790 // reaching this method.
1791 const auto& onlinePriority = onlineClientDesc->getPriority();
1792 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1793 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1794 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1795 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1796
1797 // Allow only one offline device per camera
1798 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1799 if (!incompatibleClients.empty()) {
1800 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1801 return BAD_VALUE;
1802 }
1803
1804 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1805 if (err != OK) {
1806 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1807 return err;
1808 }
1809
1810 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1811 if (evicted.size() > 0) {
1812 for (auto& i : evicted) {
1813 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1814 __FUNCTION__, i->getKey().string());
1815 }
1816
1817 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1818 "properly", __FUNCTION__);
1819
1820 return BAD_VALUE;
1821 }
1822
1823 logConnectedOffline(offlineClientDesc->getKey(),
1824 static_cast<int>(offlineClientDesc->getOwnerId()),
1825 String8(offlineClient->getPackageName()));
1826
1827 sp<IBinder> remoteCallback = offlineClient->getRemote();
1828 if (remoteCallback != nullptr) {
1829 remoteCallback->linkToDeath(this);
1830 }
1831 } // lock is destroyed, allow further connect calls
1832
1833 return OK;
1834}
1835
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001836Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001837 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001838 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001839
1840 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001841 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001842 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001843 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1844 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001845 }
1846
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001847 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001848 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001849
1850 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 auto state = getCameraState(id);
1852 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001853 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001854 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1855 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 }
1857
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001858 StatusInternal cameraStatus = state->getStatus();
1859 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001860 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1861 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001862 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1863 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001864 }
1865
1866 {
1867 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001868 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001869 status_t err = getTorchStatusLocked(id, &status);
1870 if (err != OK) {
1871 if (err == NAME_NOT_FOUND) {
1872 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1873 "Camera \"%s\" does not have a flash unit", id.string());
1874 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001875 ALOGE("%s: getting current torch status failed for camera %s",
1876 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001877 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1878 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1879 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001880 }
1881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001882 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001883 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001884 ALOGE("%s: torch mode of camera %s is not available because "
1885 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001886 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1887 "Torch for camera \"%s\" is not available due to an existing camera user",
1888 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001889 } else {
1890 ALOGE("%s: torch mode of camera %s is not available due to "
1891 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001892 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1893 "Torch for camera \"%s\" is not available due to insufficient resources",
1894 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001895 }
1896 }
1897 }
1898
Ruben Brunk99e69712015-05-26 17:25:07 -07001899 {
1900 // Update UID map - this is used in the torch status changed callbacks, so must be done
1901 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001902 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001903 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1904 mTorchUidMap[id].first = uid;
1905 mTorchUidMap[id].second = uid;
1906 } else {
1907 // Set the pending UID
1908 mTorchUidMap[id].first = uid;
1909 }
1910 }
1911
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001912 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001913
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001914 if (err != OK) {
1915 int32_t errorCode;
1916 String8 msg;
1917 switch (err) {
1918 case -ENOSYS:
1919 msg = String8::format("Camera \"%s\" has no flashlight",
1920 id.string());
1921 errorCode = ERROR_ILLEGAL_ARGUMENT;
1922 break;
1923 default:
1924 msg = String8::format(
1925 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1926 id.string(), enabled, strerror(-err), err);
1927 errorCode = ERROR_INVALID_OPERATION;
1928 }
1929 ALOGE("%s: %s", __FUNCTION__, msg.string());
1930 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001931 }
1932
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001933 {
1934 // update the link to client's death
1935 Mutex::Autolock al(mTorchClientMapMutex);
1936 ssize_t index = mTorchClientMap.indexOfKey(id);
1937 if (enabled) {
1938 if (index == NAME_NOT_FOUND) {
1939 mTorchClientMap.add(id, clientBinder);
1940 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001941 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001942 mTorchClientMap.replaceValueAt(index, clientBinder);
1943 }
1944 clientBinder->linkToDeath(this);
1945 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001946 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001947 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001948 }
1949
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001950 int clientPid = CameraThreadState::getCallingPid();
1951 const char *id_cstr = id.c_str();
1952 const char *torchState = enabled ? "on" : "off";
1953 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1954 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001955 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001956}
1957
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001958Status CameraService::notifySystemEvent(int32_t eventId,
1959 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001960 const int pid = CameraThreadState::getCallingPid();
1961 const int selfPid = getpid();
1962
1963 // Permission checks
1964 if (pid != selfPid) {
1965 // Ensure we're being called by system_server, or similar process with
1966 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001967 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001968 const int uid = CameraThreadState::getCallingUid();
1969 ALOGE("Permission Denial: cannot send updates to camera service about system"
1970 " events from pid=%d, uid=%d", pid, uid);
1971 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001972 "No permission to send updates to camera service about system events"
1973 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001974 }
1975 }
1976
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001977 ATRACE_CALL();
1978
Ruben Brunk36597b22015-03-20 22:15:57 -07001979 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001980 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001981 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001982 // from a system server crash
1983 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08001984 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001985 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07001986 break;
1987 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001988 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07001989 default: {
1990 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1991 eventId);
1992 break;
1993 }
1994 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001995 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07001996}
1997
Emilian Peev53722fa2019-02-22 17:47:20 -08001998void CameraService::notifyMonitoredUids() {
1999 Mutex::Autolock lock(mStatusListenerLock);
2000
2001 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002002 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002003 if (!ret.isOk()) {
2004 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2005 ret.exceptionCode());
2006 }
2007 }
2008}
2009
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002010Status CameraService::notifyDeviceStateChange(int64_t newState) {
2011 const int pid = CameraThreadState::getCallingPid();
2012 const int selfPid = getpid();
2013
2014 // Permission checks
2015 if (pid != selfPid) {
2016 // Ensure we're being called by system_server, or similar process with
2017 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002018 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002019 const int uid = CameraThreadState::getCallingUid();
2020 ALOGE("Permission Denial: cannot send updates to camera service about device"
2021 " state changes from pid=%d, uid=%d", pid, uid);
2022 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2023 "No permission to send updates to camera service about device state"
2024 " changes from pid=%d, uid=%d", pid, uid);
2025 }
2026 }
2027
2028 ATRACE_CALL();
2029
2030 using hardware::camera::provider::V2_5::DeviceState;
2031 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2032 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2033 newDeviceState |= DeviceState::BACK_COVERED;
2034 }
2035 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2036 newDeviceState |= DeviceState::FRONT_COVERED;
2037 }
2038 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2039 newDeviceState |= DeviceState::FOLDED;
2040 }
2041 // Only map vendor bits directly
2042 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2043 newDeviceState |= vendorBits;
2044
2045 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2046 Mutex::Autolock l(mServiceLock);
2047 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2048
2049 return Status::ok();
2050}
2051
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002052 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002053 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2054 ATRACE_CALL();
2055 if (!concurrentCameraIds) {
2056 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2057 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2058 }
2059
2060 if (!mInitialized) {
2061 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2062 return STATUS_ERROR(ERROR_DISCONNECTED,
2063 "Camera subsystem is not available");
2064 }
2065 // First call into the provider and get the set of concurrent camera
2066 // combinations
2067 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002068 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002069 for (auto &combination : concurrentCameraCombinations) {
2070 std::vector<std::string> validCombination;
2071 for (auto &cameraId : combination) {
2072 // if the camera state is not present, skip
2073 String8 cameraIdStr(cameraId.c_str());
2074 auto state = getCameraState(cameraIdStr);
2075 if (state == nullptr) {
2076 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2077 continue;
2078 }
2079 StatusInternal status = state->getStatus();
2080 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2081 continue;
2082 }
2083 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2084 continue;
2085 }
2086 validCombination.push_back(cameraId);
2087 }
2088 if (validCombination.size() != 0) {
2089 concurrentCameraIds->push_back(std::move(validCombination));
2090 }
2091 }
2092 return Status::ok();
2093}
2094
2095Status CameraService::isConcurrentSessionConfigurationSupported(
2096 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2097 /*out*/bool* isSupported) {
2098 if (!isSupported) {
2099 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2100 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2101 }
2102
2103 if (!mInitialized) {
2104 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2105 return STATUS_ERROR(ERROR_DISCONNECTED,
2106 "Camera subsystem is not available");
2107 }
2108
2109 // Check for camera permissions
2110 int callingPid = CameraThreadState::getCallingPid();
2111 int callingUid = CameraThreadState::getCallingUid();
2112 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2113 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2114 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2115 "android.permission.CAMERA needed to call"
2116 "isConcurrentSessionConfigurationSupported");
2117 }
2118
2119 status_t res =
2120 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2121 cameraIdsAndSessionConfigurations, isSupported);
2122 if (res != OK) {
2123 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2124 "support %s (%d)", strerror(-res), res);
2125 }
2126 return Status::ok();
2127}
2128
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002129Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2130 /*out*/
2131 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002132 return addListenerHelper(listener, cameraStatuses);
2133}
2134
2135Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2136 /*out*/
2137 std::vector<hardware::CameraStatus> *cameraStatuses,
2138 bool isVendorListener) {
2139
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002140 ATRACE_CALL();
2141
Igor Murashkinbfc99152013-02-27 12:55:20 -08002142 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002143
Ruben Brunk3450ba72015-06-16 11:00:37 -07002144 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002145 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002146 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002147 }
2148
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002149 auto clientUid = CameraThreadState::getCallingUid();
2150 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002151 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2152 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002153
Igor Murashkinbfc99152013-02-27 12:55:20 -08002154 Mutex::Autolock lock(mServiceLock);
2155
Ruben Brunkcc776712015-02-17 20:18:47 -08002156 {
2157 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002158 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002159 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002160 ALOGW("%s: Tried to add listener %p which was already subscribed",
2161 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002162 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002163 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002164 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002165
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002166 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002167 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2168 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002169 auto ret = serviceListener->initialize();
2170 if (ret != NO_ERROR) {
2171 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2172 strerror(-ret), ret);
2173 ALOGE("%s: %s", __FUNCTION__, msg.string());
2174 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2175 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002176 // The listener still needs to be added to the list of listeners, regardless of what
2177 // permissions the listener process has / whether it is a vendor listener. Since it might be
2178 // eligible to listen to other camera ids.
2179 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002180 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002181 }
2182
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002183 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002184 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002185 Mutex::Autolock lock(mCameraStatesLock);
2186 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002187 cameraStatuses->emplace_back(i.first,
2188 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002189 }
2190 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002191 // Remove the camera statuses that should be hidden from the client, we do
2192 // this after collecting the states in order to avoid holding
2193 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2194 // the same time.
2195 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2196 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2197 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2198 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2199 ALOGE("%s: Invalid camera id %s, skipping status update",
2200 __FUNCTION__, s.cameraId.c_str());
2201 return true;
2202 }
2203 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2204 clientUid);}), cameraStatuses->end());
2205
Igor Murashkincba2c162013-03-20 15:56:31 -07002206
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002207 /*
2208 * Immediately signal current torch status to this listener only
2209 * This may be a subset of all the devices, so don't include it in the response directly
2210 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002211 {
2212 Mutex::Autolock al(mTorchStatusMutex);
2213 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002214 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002215 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002216 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002217 }
2218
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002219 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002220}
Ruben Brunkcc776712015-02-17 20:18:47 -08002221
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002222Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002223 ATRACE_CALL();
2224
Igor Murashkinbfc99152013-02-27 12:55:20 -08002225 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2226
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002227 if (listener == 0) {
2228 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002230 }
2231
Igor Murashkinbfc99152013-02-27 12:55:20 -08002232 Mutex::Autolock lock(mServiceLock);
2233
Ruben Brunkcc776712015-02-17 20:18:47 -08002234 {
2235 Mutex::Autolock lock(mStatusListenerLock);
2236 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002237 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2238 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2239 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002240 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002241 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002242 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002243 }
2244 }
2245
2246 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2247 __FUNCTION__, listener.get());
2248
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002250}
2251
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002252Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002253
2254 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002255 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2256
2257 if (parameters == NULL) {
2258 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002260 }
2261
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002262 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002263
2264 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002266 // Error logged by caller
2267 return ret;
2268 }
2269
2270 String8 shimParamsString8 = shimParams.flatten();
2271 String16 shimParamsString16 = String16(shimParamsString8);
2272
2273 *parameters = shimParamsString16;
2274
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002275 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002276}
2277
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002278Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2279 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002280 ATRACE_CALL();
2281
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002282 const String8 id = String8(cameraId);
2283
2284 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002285
2286 switch (apiVersion) {
2287 case API_VERSION_1:
2288 case API_VERSION_2:
2289 break;
2290 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002291 String8 msg = String8::format("Unknown API version %d", apiVersion);
2292 ALOGE("%s: %s", __FUNCTION__, msg.string());
2293 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002294 }
2295
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002296 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002297 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002298 case CAMERA_DEVICE_API_VERSION_1_0:
2299 case CAMERA_DEVICE_API_VERSION_3_0:
2300 case CAMERA_DEVICE_API_VERSION_3_1:
2301 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002302 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2303 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002304 *isSupported = false;
2305 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002306 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2307 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002308 *isSupported = true;
2309 }
2310 break;
2311 case CAMERA_DEVICE_API_VERSION_3_2:
2312 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002313 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002314 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002315 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002316 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2317 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002318 *isSupported = true;
2319 break;
2320 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002321 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002322 ALOGE("%s: %s", __FUNCTION__, msg.string());
2323 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002324 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002325 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002326 String8 msg = String8::format("Unknown device version %x for device %s",
2327 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 ALOGE("%s: %s", __FUNCTION__, msg.string());
2329 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2330 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002331 }
2332
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002334}
2335
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002336Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2337 /*out*/ bool *isSupported) {
2338 ATRACE_CALL();
2339
2340 const String8 id = String8(cameraId);
2341
2342 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2343 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2344
2345 return Status::ok();
2346}
2347
Ruben Brunkcc776712015-02-17 20:18:47 -08002348void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002349 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002350 for (auto& i : mActiveClientManager.getAll()) {
2351 auto clientSp = i->getValue();
2352 if (clientSp.get() == client) {
2353 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002354 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002355 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002356 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002357}
2358
Ruben Brunkcc776712015-02-17 20:18:47 -08002359bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002360 bool ret = false;
2361 {
2362 // Acquire mServiceLock and prevent other clients from connecting
2363 std::unique_ptr<AutoConditionLock> lock =
2364 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002365
Igor Murashkin634a5152013-02-20 17:15:11 -08002366
Ruben Brunkcc776712015-02-17 20:18:47 -08002367 std::vector<sp<BasicClient>> evicted;
2368 for (auto& i : mActiveClientManager.getAll()) {
2369 auto clientSp = i->getValue();
2370 if (clientSp.get() == nullptr) {
2371 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2372 mActiveClientManager.remove(i);
2373 continue;
2374 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002375 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002376 mActiveClientManager.remove(i);
2377 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002378
Ruben Brunkcc776712015-02-17 20:18:47 -08002379 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002380 clientSp->notifyError(
2381 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002382 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002383 }
2384 }
2385
Ruben Brunkcc776712015-02-17 20:18:47 -08002386 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2387 // other clients from connecting in mServiceLockWrapper if held
2388 mServiceLock.unlock();
2389
Ruben Brunk36597b22015-03-20 22:15:57 -07002390 // Do not clear caller identity, remote caller should be client proccess
2391
Ruben Brunkcc776712015-02-17 20:18:47 -08002392 for (auto& i : evicted) {
2393 if (i.get() != nullptr) {
2394 i->disconnect();
2395 ret = true;
2396 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002397 }
2398
Ruben Brunkcc776712015-02-17 20:18:47 -08002399 // Reacquire mServiceLock
2400 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002401
Ruben Brunkcc776712015-02-17 20:18:47 -08002402 } // lock is destroyed, allow further connect calls
2403
2404 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002405}
2406
Ruben Brunkcc776712015-02-17 20:18:47 -08002407std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2408 const String8& cameraId) const {
2409 std::shared_ptr<CameraState> state;
2410 {
2411 Mutex::Autolock lock(mCameraStatesLock);
2412 auto iter = mCameraStates.find(cameraId);
2413 if (iter != mCameraStates.end()) {
2414 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 }
2416 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002417 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418}
2419
Ruben Brunkcc776712015-02-17 20:18:47 -08002420sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2421 // Remove from active clients list
2422 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2423 if (clientDescriptorPtr == nullptr) {
2424 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2425 cameraId.string());
2426 return sp<BasicClient>{nullptr};
2427 }
2428
2429 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002430}
2431
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002432void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002433 // Acquire mServiceLock and prevent other clients from connecting
2434 std::unique_ptr<AutoConditionLock> lock =
2435 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2436
Ruben Brunk6267b532015-04-30 17:44:07 -07002437 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002438 for (size_t i = 0; i < newUserIds.size(); i++) {
2439 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002440 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002441 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002442 return;
2443 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002444 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002445 }
2446
Ruben Brunka8ca9152015-04-07 14:23:40 -07002447
Ruben Brunk6267b532015-04-30 17:44:07 -07002448 if (newAllowedUsers == mAllowedUsers) {
2449 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2450 return;
2451 }
2452
2453 logUserSwitch(mAllowedUsers, newAllowedUsers);
2454
2455 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002456
2457 // Current user has switched, evict all current clients.
2458 std::vector<sp<BasicClient>> evicted;
2459 for (auto& i : mActiveClientManager.getAll()) {
2460 auto clientSp = i->getValue();
2461
2462 if (clientSp.get() == nullptr) {
2463 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2464 continue;
2465 }
2466
Ruben Brunk6267b532015-04-30 17:44:07 -07002467 // Don't evict clients that are still allowed.
2468 uid_t clientUid = clientSp->getClientUid();
2469 userid_t clientUserId = multiuser_get_user_id(clientUid);
2470 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2471 continue;
2472 }
2473
Ruben Brunk36597b22015-03-20 22:15:57 -07002474 evicted.push_back(clientSp);
2475
2476 String8 curTime = getFormattedCurrentTime();
2477
2478 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2479 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002480
Ruben Brunk36597b22015-03-20 22:15:57 -07002481 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002482 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002483 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2484 " to user switch.", i->getKey().string(),
2485 String8{clientSp->getPackageName()}.string(),
2486 i->getOwnerId(), i->getPriority().getScore(),
2487 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002488
2489 }
2490
2491 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2492 // blocking other clients from connecting in mServiceLockWrapper if held.
2493 mServiceLock.unlock();
2494
2495 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002496 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002497
2498 for (auto& i : evicted) {
2499 i->disconnect();
2500 }
2501
Jayant Chowdhary12361932018-08-27 14:46:13 -07002502 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002503
2504 // Reacquire mServiceLock
2505 mServiceLock.lock();
2506}
Ruben Brunkcc776712015-02-17 20:18:47 -08002507
Ruben Brunka8ca9152015-04-07 14:23:40 -07002508void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002509 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002510 Mutex::Autolock l(mLogLock);
2511 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512}
2513
Ruben Brunka8ca9152015-04-07 14:23:40 -07002514void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002515 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002516 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002517 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002518 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002519}
2520
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002521void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2522 const char* clientPackage) {
2523 // Log the clients evicted
2524 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2525 cameraId, clientPackage, clientPid));
2526}
2527
Ruben Brunka8ca9152015-04-07 14:23:40 -07002528void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002529 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002530 // Log the clients evicted
2531 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002532 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002533}
2534
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002535void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2536 const char* clientPackage) {
2537 // Log the clients evicted
2538 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2539 clientPackage, clientPid));
2540}
2541
Ruben Brunka8ca9152015-04-07 14:23:40 -07002542void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002543 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002544 // Log the client rejected
2545 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002546 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002547}
2548
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002549void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2550 // Log torch event
2551 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2552 torchState, clientPid));
2553}
2554
Ruben Brunk6267b532015-04-30 17:44:07 -07002555void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2556 const std::set<userid_t>& newUserIds) {
2557 String8 newUsers = toString(newUserIds);
2558 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002559 if (oldUsers.size() == 0) {
2560 oldUsers = "<None>";
2561 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002562 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002563 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002564 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002565}
2566
2567void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2568 // Log the device removal
2569 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2570}
2571
2572void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2573 // Log the device removal
2574 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2575}
2576
2577void CameraService::logClientDied(int clientPid, const char* reason) {
2578 // Log the device removal
2579 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002580}
2581
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002582void CameraService::logServiceError(const char* msg, int errorCode) {
2583 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002584 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002585}
2586
Ruben Brunk36597b22015-03-20 22:15:57 -07002587status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2588 uint32_t flags) {
2589
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 // Permission checks
2591 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002592 case SHELL_COMMAND_TRANSACTION: {
2593 int in = data.readFileDescriptor();
2594 int out = data.readFileDescriptor();
2595 int err = data.readFileDescriptor();
2596 int argc = data.readInt32();
2597 Vector<String16> args;
2598 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2599 args.add(data.readString16());
2600 }
2601 sp<IBinder> unusedCallback;
2602 sp<IResultReceiver> resultReceiver;
2603 status_t status;
2604 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2605 return status;
2606 }
2607 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2608 return status;
2609 }
2610 status = shellCommand(in, out, err, args);
2611 if (resultReceiver != nullptr) {
2612 resultReceiver->send(status);
2613 }
2614 return NO_ERROR;
2615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 }
2617
2618 return BnCameraService::onTransact(code, data, reply, flags);
2619}
2620
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621// We share the media players for shutter and recording sound for all clients.
2622// A reference count is kept to determine when we will actually release the
2623// media players.
2624
Jaekyun Seokef498052018-03-23 13:09:44 +09002625sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2626 sp<MediaPlayer> mp = new MediaPlayer();
2627 status_t error;
2628 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002629 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002630 error = mp->prepare();
2631 }
2632 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002633 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002634 mp->disconnect();
2635 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002636 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 }
2638 return mp;
2639}
2640
username5755fea2018-12-27 09:48:08 +08002641void CameraService::increaseSoundRef() {
2642 Mutex::Autolock lock(mSoundLock);
2643 mSoundRef++;
2644}
2645
2646void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002647 ATRACE_CALL();
2648
username5755fea2018-12-27 09:48:08 +08002649 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2650 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2651 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2652 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2653 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2654 }
2655 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2656 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2657 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2658 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002659 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002660 }
2661 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2662 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2663 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2664 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2665 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667}
2668
username5755fea2018-12-27 09:48:08 +08002669void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002671 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 if (--mSoundRef) return;
2673
2674 for (int i = 0; i < NUM_SOUNDS; i++) {
2675 if (mSoundPlayer[i] != 0) {
2676 mSoundPlayer[i]->disconnect();
2677 mSoundPlayer[i].clear();
2678 }
2679 }
2680}
2681
2682void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002683 ATRACE_CALL();
2684
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 LOG1("playSound(%d)", kind);
2686 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002687 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 sp<MediaPlayer> player = mSoundPlayer[kind];
2689 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002690 player->seekTo(0);
2691 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 }
2693}
2694
2695// ----------------------------------------------------------------------------
2696
2697CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002698 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002699 const String16& clientPackageName,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002700 const std::unique_ptr<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002701 const String8& cameraIdStr,
2702 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002703 int clientPid, uid_t clientUid,
2704 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002705 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002706 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002707 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002708 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002709 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002710 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002711 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002712{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002713 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002714 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002716 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717
username5755fea2018-12-27 09:48:08 +08002718 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002719
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002720 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721}
2722
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723// tear down the client
2724CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002725 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002726 mDestructionStarted = true;
2727
username5755fea2018-12-27 09:48:08 +08002728 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002729 // unconditionally disconnect. function is idempotent
2730 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731}
2732
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002733sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2734
Igor Murashkin634a5152013-02-20 17:15:11 -08002735CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002736 const sp<IBinder>& remoteCallback,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002737 const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002738 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002739 int clientPid, uid_t clientUid,
2740 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002741 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002742 mClientPackageName(clientPackageName),
2743 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002744 mServicePid(servicePid),
2745 mDisconnected(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002746 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002747 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002748{
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002749 if (clientFeatureId) {
2750 mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
2751 } else {
2752 mClientFeatureId = std::unique_ptr<String16>();
2753 }
2754
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002755 if (sCameraService == nullptr) {
2756 sCameraService = cameraService;
2757 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002758 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002759 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002760
2761 // In some cases the calling code has no access to the package it runs under.
2762 // For example, NDK camera API.
2763 // In this case we will get the packages for the calling UID and pick the first one
2764 // for attributing the app op. This will work correctly for runtime permissions
2765 // as for legacy apps we will toggle the app op for all packages in the UID.
2766 // The caveat is that the operation may be attributed to the wrong package and
2767 // stats based on app ops may be slightly off.
2768 if (mClientPackageName.size() <= 0) {
2769 sp<IServiceManager> sm = defaultServiceManager();
2770 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2771 if (binder == 0) {
2772 ALOGE("Cannot get permission service");
2773 // Leave mClientPackageName unchanged (empty) and the further interaction
2774 // with camera will fail in BasicClient::startCameraOps
2775 return;
2776 }
2777
2778 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2779 Vector<String16> packages;
2780
2781 permCtrl->getPackagesForUid(mClientUid, packages);
2782
2783 if (packages.isEmpty()) {
2784 ALOGE("No packages for calling UID");
2785 // Leave mClientPackageName unchanged (empty) and the further interaction
2786 // with camera will fail in BasicClient::startCameraOps
2787 return;
2788 }
2789 mClientPackageName = packages[0];
2790 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002791 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002792 mAppOpsManager = std::make_unique<AppOpsManager>();
2793 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002794}
2795
2796CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002797 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002798 mDestructionStarted = true;
2799}
2800
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002801binder::Status CameraService::BasicClient::disconnect() {
2802 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002803 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002804 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002805 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002806 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002807
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002808 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002809 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002810 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2811 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002812
2813 sp<IBinder> remote = getRemote();
2814 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002815 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002816 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002817
2818 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002819 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002820 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2821 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2822 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002823
Igor Murashkincba2c162013-03-20 15:56:31 -07002824 // client shouldn't be able to call into us anymore
2825 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002826
2827 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002828}
2829
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002830status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2831 // No dumping of clients directly over Binder,
2832 // must go through CameraService::dump
2833 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002834 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002835 return OK;
2836}
2837
Ruben Brunkcc776712015-02-17 20:18:47 -08002838String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002839 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002840}
2841
2842
2843int CameraService::BasicClient::getClientPid() const {
2844 return mClientPid;
2845}
2846
Ruben Brunk6267b532015-04-30 17:44:07 -07002847uid_t CameraService::BasicClient::getClientUid() const {
2848 return mClientUid;
2849}
2850
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002851bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2852 // Defaults to API2.
2853 return level == API_2;
2854}
2855
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002856status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002857 {
2858 Mutex::Autolock l(mAudioRestrictionLock);
2859 mAudioRestriction = mode;
2860 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002861 sCameraService->updateAudioRestriction();
2862 return OK;
2863}
2864
2865int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002866 return sCameraService->updateAudioRestriction();
2867}
2868
2869int32_t CameraService::BasicClient::getAudioRestriction() const {
2870 Mutex::Autolock l(mAudioRestrictionLock);
2871 return mAudioRestriction;
2872}
2873
2874bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2875 switch (mode) {
2876 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2877 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2878 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2879 return true;
2880 default:
2881 return false;
2882 }
2883}
2884
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002885status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002886 ATRACE_CALL();
2887
Igor Murashkine6800ce2013-03-04 17:25:57 -08002888 {
2889 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002890 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002891 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002892 if (mAppOpsManager != nullptr) {
2893 // Notify app ops that the camera is not available
2894 mOpsCallback = new OpsCallback(this);
2895 int32_t res;
2896 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2897 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002898 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2899 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2900 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002901
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002902 if (res == AppOpsManager::MODE_ERRORED) {
2903 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2904 mCameraIdStr.string(), String8(mClientPackageName).string());
2905 return PERMISSION_DENIED;
2906 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002907
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002908 if (res == AppOpsManager::MODE_IGNORED) {
2909 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2910 mCameraIdStr.string(), String8(mClientPackageName).string());
2911 // Return the same error as for device policy manager rejection
2912 return -EACCES;
2913 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002914 }
2915
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002916 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002917
2918 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002919 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002920
Emilian Peev573291c2018-02-10 02:10:56 +00002921 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2922 if (canCastToApiClient(API_2)) {
2923 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2924 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002925 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002926 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002927 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002928
Emilian Peev53722fa2019-02-22 17:47:20 -08002929 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2930
Shuzhen Wang695044d2020-03-06 09:02:23 -08002931 // Notify listeners of camera open/close status
2932 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2933
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002934 return OK;
2935}
2936
2937status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002938 ATRACE_CALL();
2939
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002940 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002941 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002942 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002943 if (mAppOpsManager != nullptr) {
2944 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002945 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002946 mOpsActive = false;
2947 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002948 // This function is called when a client disconnects. This should
2949 // release the camera, but actually only if it was in a proper
2950 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002951 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002952 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002953
Ruben Brunkcc776712015-02-17 20:18:47 -08002954 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002955 sCameraService->updateStatus(StatusInternal::PRESENT,
2956 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002957
Emilian Peev573291c2018-02-10 02:10:56 +00002958 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2959 if (canCastToApiClient(API_2)) {
2960 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2961 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002962 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002963 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002964 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002965 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002966 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002967 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2968 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002969 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002970 mOpsCallback.clear();
2971
Emilian Peev53722fa2019-02-22 17:47:20 -08002972 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2973
Shuzhen Wang695044d2020-03-06 09:02:23 -08002974 // Notify listeners of camera open/close status
2975 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2976
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002977 return OK;
2978}
2979
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002980void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002981 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002982 if (mAppOpsManager == nullptr) {
2983 return;
2984 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002985 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002986 if (op != AppOpsManager::OP_CAMERA) {
2987 ALOGW("Unexpected app ops notification received: %d", op);
2988 return;
2989 }
2990
2991 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002992 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002993 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002994 ALOGV("checkOp returns: %d, %s ", res,
2995 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2996 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2997 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2998 "UNKNOWN");
2999
3000 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003001 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003002 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003003 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003004 }
3005}
3006
Svet Ganova453d0d2018-01-11 15:37:58 -08003007void CameraService::BasicClient::block() {
3008 ATRACE_CALL();
3009
3010 // Reset the client PID to allow server-initiated disconnect,
3011 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003012 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003013 CaptureResultExtras resultExtras; // a dummy result (invalid)
3014 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3015 disconnect();
3016}
3017
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018// ----------------------------------------------------------------------------
3019
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003020void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003021 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003022 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003023 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003024 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3025 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3026 api1ErrorCode = CAMERA_ERROR_DISABLED;
3027 }
3028 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003029 } else {
3030 ALOGE("mRemoteCallback is NULL!!");
3031 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003032}
3033
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003034// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003035binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003036 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003037 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003038}
3039
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003040bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3041 return level == API_1;
3042}
3043
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003044CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3045 mClient(client) {
3046}
3047
3048void CameraService::Client::OpsCallback::opChanged(int32_t op,
3049 const String16& packageName) {
3050 sp<BasicClient> client = mClient.promote();
3051 if (client != NULL) {
3052 client->opChanged(op, packageName);
3053 }
3054}
3055
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003057// UidPolicy
3058// ----------------------------------------------------------------------------
3059
3060void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003061 Mutex::Autolock _l(mUidLock);
3062
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003063 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003064 status_t res = mAm.linkToDeath(this);
3065 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003066 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003067 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003068 ActivityManager::PROCESS_STATE_UNKNOWN,
3069 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003070 if (res == OK) {
3071 mRegistered = true;
3072 ALOGV("UidPolicy: Registered with ActivityManager");
3073 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003074}
3075
3076void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003077 Mutex::Autolock _l(mUidLock);
3078
Steven Moreland2f348142019-07-02 15:59:07 -07003079 mAm.unregisterUidObserver(this);
3080 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003081 mRegistered = false;
3082 mActiveUids.clear();
3083 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003084}
3085
3086void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3087 onUidIdle(uid, disabled);
3088}
3089
3090void CameraService::UidPolicy::onUidActive(uid_t uid) {
3091 Mutex::Autolock _l(mUidLock);
3092 mActiveUids.insert(uid);
3093}
3094
3095void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3096 bool deleted = false;
3097 {
3098 Mutex::Autolock _l(mUidLock);
3099 if (mActiveUids.erase(uid) > 0) {
3100 deleted = true;
3101 }
3102 }
3103 if (deleted) {
3104 sp<CameraService> service = mService.promote();
3105 if (service != nullptr) {
3106 service->blockClientsForUid(uid);
3107 }
3108 }
3109}
3110
Emilian Peev53722fa2019-02-22 17:47:20 -08003111void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003112 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003113 bool procStateChange = false;
3114 {
3115 Mutex::Autolock _l(mUidLock);
3116 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3117 (mMonitoredUids[uid].first != procState)) {
3118 mMonitoredUids[uid].first = procState;
3119 procStateChange = true;
3120 }
3121 }
3122
3123 if (procStateChange) {
3124 sp<CameraService> service = mService.promote();
3125 if (service != nullptr) {
3126 service->notifyMonitoredUids();
3127 }
3128 }
3129}
3130
3131void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3132 Mutex::Autolock _l(mUidLock);
3133 auto it = mMonitoredUids.find(uid);
3134 if (it != mMonitoredUids.end()) {
3135 it->second.second++;
3136 } else {
3137 mMonitoredUids.emplace(
3138 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3139 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3140 }
3141}
3142
3143void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3144 Mutex::Autolock _l(mUidLock);
3145 auto it = mMonitoredUids.find(uid);
3146 if (it != mMonitoredUids.end()) {
3147 it->second.second--;
3148 if (it->second.second == 0) {
3149 mMonitoredUids.erase(it);
3150 }
3151 } else {
3152 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3153 }
3154}
3155
Svet Ganov7b4ab782018-03-25 12:48:10 -07003156bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003157 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003158 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003159}
3160
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003161static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3162static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003163
Svet Ganov7b4ab782018-03-25 12:48:10 -07003164bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003165 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003166 // If activity manager is unreachable, assume everything is active
3167 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003168 return true;
3169 }
3170 auto it = mOverrideUids.find(uid);
3171 if (it != mOverrideUids.end()) {
3172 return it->second;
3173 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003174 bool active = mActiveUids.find(uid) != mActiveUids.end();
3175 if (!active) {
3176 // We want active UIDs to always access camera with their first attempt since
3177 // there is no guarantee the app is robustly written and would retry getting
3178 // the camera on failure. The inverse case is not a problem as we would take
3179 // camera away soon once we get the callback that the uid is no longer active.
3180 ActivityManager am;
3181 // Okay to access with a lock held as UID changes are dispatched without
3182 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003183 int64_t startTimeMillis = 0;
3184 do {
3185 // TODO: Fix this b/109950150!
3186 // Okay this is a hack. There is a race between the UID turning active and
3187 // activity being resumed. The proper fix is very risky, so we temporary add
3188 // some polling which should happen pretty rarely anyway as the race is hard
3189 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003190 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yuffffffc2020-03-24 16:13:59 -07003191 if (!active) {
3192 active = am.isUidActiveOrForeground(uid, callingPackage);
3193 }
Svet Ganov94ec46f2018-06-08 15:03:46 -07003194 if (active) {
3195 break;
3196 }
3197 if (startTimeMillis <= 0) {
3198 startTimeMillis = uptimeMillis();
3199 }
3200 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003201 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003202 if (remainingTimeMillis <= 0) {
3203 break;
3204 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003205 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3206
3207 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003208 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003209 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003210 } while (true);
3211
Svet Ganov7b4ab782018-03-25 12:48:10 -07003212 if (active) {
3213 // Now that we found out the UID is actually active, cache that
3214 mActiveUids.insert(uid);
3215 }
3216 }
3217 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003218}
3219
Varun Shahb42f1eb2019-04-16 14:45:13 -07003220int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3221 Mutex::Autolock _l(mUidLock);
3222 return getProcStateLocked(uid);
3223}
3224
3225int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3226 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3227 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3228 procState = mMonitoredUids[uid].first;
3229 }
3230 return procState;
3231}
3232
Svet Ganov7b4ab782018-03-25 12:48:10 -07003233void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3234 String16 callingPackage, bool active) {
3235 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003236}
3237
Svet Ganov7b4ab782018-03-25 12:48:10 -07003238void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3239 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003240}
3241
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003242void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3243 Mutex::Autolock _l(mUidLock);
3244 ALOGV("UidPolicy: ActivityManager has died");
3245 mRegistered = false;
3246 mActiveUids.clear();
3247}
3248
Svet Ganov7b4ab782018-03-25 12:48:10 -07003249void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3250 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003251 bool wasActive = false;
3252 bool isActive = false;
3253 {
3254 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003255 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003256 mOverrideUids.erase(uid);
3257 if (insert) {
3258 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3259 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003260 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003261 }
3262 if (wasActive != isActive && !isActive) {
3263 sp<CameraService> service = mService.promote();
3264 if (service != nullptr) {
3265 service->blockClientsForUid(uid);
3266 }
3267 }
3268}
3269
3270// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003271// SensorPrivacyPolicy
3272// ----------------------------------------------------------------------------
3273void CameraService::SensorPrivacyPolicy::registerSelf() {
3274 Mutex::Autolock _l(mSensorPrivacyLock);
3275 if (mRegistered) {
3276 return;
3277 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003278 mSpm.addSensorPrivacyListener(this);
3279 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3280 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003281 if (res == OK) {
3282 mRegistered = true;
3283 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3284 }
3285}
3286
3287void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3288 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003289 mSpm.removeSensorPrivacyListener(this);
3290 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003291 mRegistered = false;
3292 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3293}
3294
3295bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3296 Mutex::Autolock _l(mSensorPrivacyLock);
3297 return mSensorPrivacyEnabled;
3298}
3299
3300binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3301 {
3302 Mutex::Autolock _l(mSensorPrivacyLock);
3303 mSensorPrivacyEnabled = enabled;
3304 }
3305 // if sensor privacy is enabled then block all clients from accessing the camera
3306 if (enabled) {
3307 sp<CameraService> service = mService.promote();
3308 if (service != nullptr) {
3309 service->blockAllClients();
3310 }
3311 }
3312 return binder::Status::ok();
3313}
3314
3315void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3316 Mutex::Autolock _l(mSensorPrivacyLock);
3317 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3318 mRegistered = false;
3319}
3320
3321// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003322// CameraState
3323// ----------------------------------------------------------------------------
3324
3325CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003326 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3327 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3328 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003329
3330CameraService::CameraState::~CameraState() {}
3331
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003332CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003333 Mutex::Autolock lock(mStatusLock);
3334 return mStatus;
3335}
3336
Shuzhen Wang43858162020-01-10 13:42:15 -08003337std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3338 Mutex::Autolock lock(mStatusLock);
3339 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3340 return res;
3341}
3342
Ruben Brunkcc776712015-02-17 20:18:47 -08003343CameraParameters CameraService::CameraState::getShimParams() const {
3344 return mShimParams;
3345}
3346
3347void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3348 mShimParams = params;
3349}
3350
3351int CameraService::CameraState::getCost() const {
3352 return mCost;
3353}
3354
3355std::set<String8> CameraService::CameraState::getConflicting() const {
3356 return mConflicting;
3357}
3358
3359String8 CameraService::CameraState::getId() const {
3360 return mId;
3361}
3362
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003363SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3364 return mSystemCameraKind;
3365}
3366
Shuzhen Wang43858162020-01-10 13:42:15 -08003367bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3368 Mutex::Autolock lock(mStatusLock);
3369 auto result = mUnavailablePhysicalIds.insert(physicalId);
3370 return result.second;
3371}
3372
3373bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3374 Mutex::Autolock lock(mStatusLock);
3375 auto count = mUnavailablePhysicalIds.erase(physicalId);
3376 return count > 0;
3377}
3378
Ruben Brunkcc776712015-02-17 20:18:47 -08003379// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003380// ClientEventListener
3381// ----------------------------------------------------------------------------
3382
3383void CameraService::ClientEventListener::onClientAdded(
3384 const resource_policy::ClientDescriptor<String8,
3385 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003386 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003387 if (basicClient.get() != nullptr) {
3388 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3389 notifier.noteStartCamera(descriptor.getKey(),
3390 static_cast<int>(basicClient->getClientUid()));
3391 }
3392}
3393
3394void CameraService::ClientEventListener::onClientRemoved(
3395 const resource_policy::ClientDescriptor<String8,
3396 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003397 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003398 if (basicClient.get() != nullptr) {
3399 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3400 notifier.noteStopCamera(descriptor.getKey(),
3401 static_cast<int>(basicClient->getClientUid()));
3402 }
3403}
3404
3405
3406// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003407// CameraClientManager
3408// ----------------------------------------------------------------------------
3409
Ruben Brunk99e69712015-05-26 17:25:07 -07003410CameraService::CameraClientManager::CameraClientManager() {
3411 setListener(std::make_shared<ClientEventListener>());
3412}
3413
Ruben Brunkcc776712015-02-17 20:18:47 -08003414CameraService::CameraClientManager::~CameraClientManager() {}
3415
3416sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3417 const String8& id) const {
3418 auto descriptor = get(id);
3419 if (descriptor == nullptr) {
3420 return sp<BasicClient>{nullptr};
3421 }
3422 return descriptor->getValue();
3423}
3424
3425String8 CameraService::CameraClientManager::toString() const {
3426 auto all = getAll();
3427 String8 ret("[");
3428 bool hasAny = false;
3429 for (auto& i : all) {
3430 hasAny = true;
3431 String8 key = i->getKey();
3432 int32_t cost = i->getCost();
3433 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003434 int32_t score = i->getPriority().getScore();
3435 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003436 auto conflicting = i->getConflicting();
3437 auto clientSp = i->getValue();
3438 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003439 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003440 if (clientSp.get() != nullptr) {
3441 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003442 uid_t clientUid = clientSp->getClientUid();
3443 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003444 }
Emilian Peev8131a262017-02-01 12:33:43 +00003445 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3446 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003447
Ruben Brunk6267b532015-04-30 17:44:07 -07003448 if (clientSp.get() != nullptr) {
3449 ret.appendFormat("User Id: %d, ", clientUserId);
3450 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003451 if (packageName.size() != 0) {
3452 ret.appendFormat("Client Package Name: %s", packageName.string());
3453 }
3454
3455 ret.append(", Conflicting Client Devices: {");
3456 for (auto& j : conflicting) {
3457 ret.appendFormat("%s, ", j.string());
3458 }
3459 ret.append("})");
3460 }
3461 if (hasAny) ret.append("\n");
3462 ret.append("]\n");
3463 return ret;
3464}
3465
3466CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3467 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003468 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3469 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003470
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003471 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003472 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3473 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3474
Ruben Brunkcc776712015-02-17 20:18:47 -08003475 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003476 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003477}
3478
3479CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3480 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3481 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003482 partial->getConflicting(), partial->getPriority().getScore(),
3483 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003484}
3485
3486// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487
3488static const int kDumpLockRetries = 50;
3489static const int kDumpLockSleep = 60000;
3490
3491static bool tryLock(Mutex& mutex)
3492{
3493 bool locked = false;
3494 for (int i = 0; i < kDumpLockRetries; ++i) {
3495 if (mutex.tryLock() == NO_ERROR) {
3496 locked = true;
3497 break;
3498 }
3499 usleep(kDumpLockSleep);
3500 }
3501 return locked;
3502}
3503
3504status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003505 ATRACE_CALL();
3506
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003507 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003508 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003509 CameraThreadState::getCallingPid(),
3510 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003511 return NO_ERROR;
3512 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003513 bool locked = tryLock(mServiceLock);
3514 // failed to lock - CameraService is probably deadlocked
3515 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003516 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003517 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003518
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003519 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003520 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003521
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003522 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003523 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003524
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003525 if (locked) mServiceLock.unlock();
3526 return NO_ERROR;
3527 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003528 dprintf(fd, "\n== Service global info: ==\n\n");
3529 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003530 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003531 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3532 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003533 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3534 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3535 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003536 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003537 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3538 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003539
3540 dumpEventLog(fd);
3541
3542 bool stateLocked = tryLock(mCameraStatesLock);
3543 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003544 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003545 }
3546
Emilian Peevbd8c5032018-02-14 23:05:40 +00003547 int argSize = args.size();
3548 for (int i = 0; i < argSize; i++) {
3549 if (args[i] == TagMonitor::kMonitorOption) {
3550 if (i + 1 < argSize) {
3551 mMonitorTags = String8(args[i + 1]);
3552 }
3553 break;
3554 }
3555 }
3556
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003557 for (auto& state : mCameraStates) {
3558 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003559
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003560 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003561
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003562 CameraParameters p = state.second->getShimParams();
3563 if (!p.isEmpty()) {
3564 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3565 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003566 }
3567
3568 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003569 if (clientDescriptor != nullptr) {
3570 dprintf(fd, " Device %s is open. Client instance dump:\n",
3571 cameraId.string());
3572 dprintf(fd, " Client priority score: %d state: %d\n",
3573 clientDescriptor->getPriority().getScore(),
3574 clientDescriptor->getPriority().getState());
3575 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3576
3577 auto client = clientDescriptor->getValue();
3578 dprintf(fd, " Client package: %s\n",
3579 String8(client->getPackageName()).string());
3580
3581 client->dumpClient(fd, args);
3582 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003583 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003584 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003585 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003586
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003587 }
3588
3589 if (stateLocked) mCameraStatesLock.unlock();
3590
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003591 if (locked) mServiceLock.unlock();
3592
Emilian Peevf53f66e2017-04-11 14:29:43 +01003593 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003594
3595 dprintf(fd, "\n== Vendor tags: ==\n\n");
3596
3597 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3598 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003599 sp<VendorTagDescriptorCache> cache =
3600 VendorTagDescriptorCache::getGlobalVendorTagCache();
3601 if (cache == NULL) {
3602 dprintf(fd, "No vendor tags.\n");
3603 } else {
3604 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3605 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003606 } else {
3607 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3608 }
3609
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003610 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003611 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003612 camera3::CameraTraces::dump(fd, args);
3613
3614 // Process dump arguments, if any
3615 int n = args.size();
3616 String16 verboseOption("-v");
3617 String16 unreachableOption("--unreachable");
3618 for (int i = 0; i < n; i++) {
3619 if (args[i] == verboseOption) {
3620 // change logging level
3621 if (i + 1 >= n) continue;
3622 String8 levelStr(args[i+1]);
3623 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003624 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003625 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003626 } else if (args[i] == unreachableOption) {
3627 // Dump memory analysis
3628 // TODO - should limit be an argument parameter?
3629 UnreachableMemoryInfo info;
3630 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3631 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003632 dprintf(fd, "\n== Unable to dump unreachable memory. "
3633 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003634 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003635 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003636 std::string s = info.ToString(/*log_contents*/ true);
3637 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 }
3639 }
3640 }
3641 return NO_ERROR;
3642}
3643
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003644void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003645 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003646
3647 Mutex::Autolock l(mLogLock);
3648 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003649 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003650 }
3651
3652 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003653 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003654 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003655 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003656 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003657 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003658}
3659
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003660void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003661 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003662 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3663 if (mTorchClientMap[i] == who) {
3664 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003665 String8 cameraId = mTorchClientMap.keyAt(i);
3666 status_t res = mFlashlight->setTorchMode(cameraId, false);
3667 if (res) {
3668 ALOGE("%s: torch client died but couldn't turn off torch: "
3669 "%s (%d)", __FUNCTION__, strerror(-res), res);
3670 return;
3671 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003672 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003673 break;
3674 }
3675 }
3676}
3677
Ruben Brunkcc776712015-02-17 20:18:47 -08003678/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003679
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003680 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003681 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3682 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003683 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003684 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003685 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003686
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003687 // check torch client
3688 handleTorchClientBinderDied(who);
3689
3690 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003691 if(!evictClientIdByRemote(who)) {
3692 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003693 return;
3694 }
3695
Ruben Brunkcc776712015-02-17 20:18:47 -08003696 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3697 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003698}
3699
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003700void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003701 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003702}
3703
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003704void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3705 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003706 // Do not lock mServiceLock here or can get into a deadlock from
3707 // connect() -> disconnect -> updateStatus
3708
3709 auto state = getCameraState(cameraId);
3710
3711 if (state == nullptr) {
3712 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3713 cameraId.string());
3714 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003715 }
3716
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003717 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3718 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3719 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3720 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3721 return;
3722 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003723 bool supportsHAL3 = false;
3724 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3725 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3726 // mInterfaceMutex together, which can lead to deadlocks)
3727 binder::Status sRet =
3728 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3729 &supportsHAL3);
3730 if (!sRet.isOk()) {
3731 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3732 __FUNCTION__, cameraId.string());
3733 return;
3734 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003735 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003736 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003737 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003738 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003739
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003740 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003741 // Update torch status if it has a flash unit.
3742 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003743 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003744 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3745 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003746 TorchModeStatus newTorchStatus =
3747 status == StatusInternal::PRESENT ?
3748 TorchModeStatus::AVAILABLE_OFF :
3749 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003750 if (torchStatus != newTorchStatus) {
3751 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3752 }
3753 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 }
3755
3756 Mutex::Autolock lock(mStatusListenerLock);
3757
Shuzhen Wang43858162020-01-10 13:42:15 -08003758 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId);
3759
Ruben Brunkcc776712015-02-17 20:18:47 -08003760 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003761 bool isVendorListener = listener->isVendorListener();
3762 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3763 listener->getListenerPid(), listener->getListenerUid()) ||
3764 (isVendorListener && !supportsHAL3)) {
3765 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003766 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003767 continue;
3768 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003769 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003770 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003771 }
3772 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003773}
3774
Shuzhen Wang695044d2020-03-06 09:02:23 -08003775void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3776 const String16& clientPackageName) {
3777 Mutex::Autolock lock(mStatusListenerLock);
3778
3779 for (const auto& it : mListenerList) {
3780 if (!it->isOpenCloseCallbackAllowed()) {
3781 continue;
3782 }
3783
3784 binder::Status ret;
3785 String16 cameraId64(cameraId);
3786 if (open) {
3787 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3788 } else {
3789 ret = it->getListener()->onCameraClosed(cameraId64);
3790 }
3791 if (!ret.isOk()) {
3792 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3793 ret.exceptionCode());
3794 }
3795 }
3796}
3797
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003798template<class Func>
3799void CameraService::CameraState::updateStatus(StatusInternal status,
3800 const String8& cameraId,
3801 std::initializer_list<StatusInternal> rejectSourceStates,
3802 Func onStatusUpdatedLocked) {
3803 Mutex::Autolock lock(mStatusLock);
3804 StatusInternal oldStatus = mStatus;
3805 mStatus = status;
3806
3807 if (oldStatus == status) {
3808 return;
3809 }
3810
3811 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3812 cameraId.string(), oldStatus, status);
3813
3814 if (oldStatus == StatusInternal::NOT_PRESENT &&
3815 (status != StatusInternal::PRESENT &&
3816 status != StatusInternal::ENUMERATING)) {
3817
3818 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3819 __FUNCTION__);
3820 mStatus = oldStatus;
3821 return;
3822 }
3823
3824 /**
3825 * Sometimes we want to conditionally do a transition.
3826 * For example if a client disconnects, we want to go to PRESENT
3827 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3828 */
3829 for (auto& rejectStatus : rejectSourceStates) {
3830 if (oldStatus == rejectStatus) {
3831 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3832 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3833 mStatus = oldStatus;
3834 return;
3835 }
3836 }
3837
3838 onStatusUpdatedLocked(cameraId, status);
3839}
3840
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003841void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003842 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003843 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3844 if (proxyBinder == nullptr) return;
3845 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003846 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003847}
3848
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003849status_t CameraService::getTorchStatusLocked(
3850 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003851 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003852 if (!status) {
3853 return BAD_VALUE;
3854 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003855 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3856 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003857 // invalid camera ID or the camera doesn't have a flash unit
3858 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003859 }
3860
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003861 *status = mTorchStatusMap.valueAt(index);
3862 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003863}
3864
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003865status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003866 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003867 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3868 if (index == NAME_NOT_FOUND) {
3869 return BAD_VALUE;
3870 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003871 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003872
3873 return OK;
3874}
3875
Shuzhen Wang43858162020-01-10 13:42:15 -08003876void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId) {
3877 Mutex::Autolock lock(mCameraStatesLock);
3878 for (const auto& state : mCameraStates) {
3879 std::vector<std::string> physicalCameraIds;
3880 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3881 // This is not a logical multi-camera.
3882 continue;
3883 }
3884 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3885 == physicalCameraIds.end()) {
3886 // cameraId is not a physical camera of this logical multi-camera.
3887 continue;
3888 }
3889
3890 String16 id16(state.first), physicalId16(cameraId);
3891 for (auto& listener : mListenerList) {
3892 listener->getListener()->onPhysicalCameraStatusChanged(status,
3893 id16, physicalId16);
3894 }
3895 }
3896}
3897
Svet Ganova453d0d2018-01-11 15:37:58 -08003898void CameraService::blockClientsForUid(uid_t uid) {
3899 const auto clients = mActiveClientManager.getAll();
3900 for (auto& current : clients) {
3901 if (current != nullptr) {
3902 const auto basicClient = current->getValue();
3903 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3904 basicClient->block();
3905 }
3906 }
3907 }
3908}
3909
Michael Grooverd1d435a2018-12-18 17:39:42 -08003910void CameraService::blockAllClients() {
3911 const auto clients = mActiveClientManager.getAll();
3912 for (auto& current : clients) {
3913 if (current != nullptr) {
3914 const auto basicClient = current->getValue();
3915 if (basicClient.get() != nullptr) {
3916 basicClient->block();
3917 }
3918 }
3919 }
3920}
3921
Svet Ganova453d0d2018-01-11 15:37:58 -08003922// NOTE: This is a remote API - make sure all args are validated
3923status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3924 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3925 return PERMISSION_DENIED;
3926 }
3927 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3928 return BAD_VALUE;
3929 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003930 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003931 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003932 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003933 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003934 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003935 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003936 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3937 return handleSetRotateAndCrop(args);
3938 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3939 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003940 } else if (args.size() == 1 && args[0] == String16("help")) {
3941 printHelp(out);
3942 return NO_ERROR;
3943 }
3944 printHelp(err);
3945 return BAD_VALUE;
3946}
3947
3948status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003949 String16 packageName = args[1];
3950
Svet Ganova453d0d2018-01-11 15:37:58 -08003951 bool active = false;
3952 if (args[2] == String16("active")) {
3953 active = true;
3954 } else if ((args[2] != String16("idle"))) {
3955 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3956 return BAD_VALUE;
3957 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003958
3959 int userId = 0;
3960 if (args.size() >= 5 && args[3] == String16("--user")) {
3961 userId = atoi(String8(args[4]));
3962 }
3963
3964 uid_t uid;
3965 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3966 return BAD_VALUE;
3967 }
3968
3969 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003970 return NO_ERROR;
3971}
3972
3973status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003974 String16 packageName = args[1];
3975
3976 int userId = 0;
3977 if (args.size() >= 4 && args[2] == String16("--user")) {
3978 userId = atoi(String8(args[3]));
3979 }
3980
3981 uid_t uid;
3982 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003983 return BAD_VALUE;
3984 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003985
3986 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08003987 return NO_ERROR;
3988}
3989
3990status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003991 String16 packageName = args[1];
3992
3993 int userId = 0;
3994 if (args.size() >= 4 && args[2] == String16("--user")) {
3995 userId = atoi(String8(args[3]));
3996 }
3997
3998 uid_t uid;
3999 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004000 return BAD_VALUE;
4001 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004002
4003 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004004 return dprintf(out, "active\n");
4005 } else {
4006 return dprintf(out, "idle\n");
4007 }
4008}
4009
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004010status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4011 int rotateValue = atoi(String8(args[1]));
4012 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4013 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4014 Mutex::Autolock lock(mServiceLock);
4015
4016 mOverrideRotateAndCropMode = rotateValue;
4017
4018 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4019
4020 const auto clients = mActiveClientManager.getAll();
4021 for (auto& current : clients) {
4022 if (current != nullptr) {
4023 const auto basicClient = current->getValue();
4024 if (basicClient.get() != nullptr) {
4025 basicClient->setRotateAndCropOverride(rotateValue);
4026 }
4027 }
4028 }
4029
4030 return OK;
4031}
4032
4033status_t CameraService::handleGetRotateAndCrop(int out) {
4034 Mutex::Autolock lock(mServiceLock);
4035
4036 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4037}
4038
Svet Ganova453d0d2018-01-11 15:37:58 -08004039status_t CameraService::printHelp(int out) {
4040 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004041 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4042 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4043 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004044 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4045 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4046 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004047 " help print this message\n");
4048}
4049
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004050int32_t CameraService::updateAudioRestriction() {
4051 Mutex::Autolock lock(mServiceLock);
4052 return updateAudioRestrictionLocked();
4053}
4054
4055int32_t CameraService::updateAudioRestrictionLocked() {
4056 int32_t mode = 0;
4057 // iterate through all active client
4058 for (const auto& i : mActiveClientManager.getAll()) {
4059 const auto clientSp = i->getValue();
4060 mode |= clientSp->getAudioRestriction();
4061 }
4062
4063 bool modeChanged = (mAudioRestriction != mode);
4064 mAudioRestriction = mode;
4065 if (modeChanged) {
4066 mAppOps.setCameraAudioRestriction(mode);
4067 }
4068 return mode;
4069}
4070
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071}; // namespace android