blob: b5de1b7eec0f8a721e086a8c59c93622132084a3 [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 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700470 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
471 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
472 if (getSystemCameraKind(id, &deviceKind) != OK) {
473 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
474 return;
475 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800476 String16 id16(id), physicalId16(physicalId);
477 Mutex::Autolock lock(mStatusListenerLock);
478 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700479 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
480 listener->getListenerPid(), listener->getListenerUid())) {
481 ALOGV("Skipping discovery callback for system-only camera device %s",
482 id.c_str());
483 continue;
484 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800485 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
486 id16, physicalId16);
487 }
488 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700489}
490
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800491void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
492 if (clientToDisconnect.get() != nullptr) {
493 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
494 __FUNCTION__, id.string());
495 // Notify the client of disconnection
496 clientToDisconnect->notifyError(
497 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
498 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800499 clientToDisconnect->disconnect();
500 }
501}
502
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800503void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800505 Mutex::Autolock al(mTorchStatusMutex);
506 onTorchStatusChangedLocked(cameraId, newStatus);
507}
508
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800509void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800510 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800511 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
512 __FUNCTION__, cameraId.string(), newStatus);
513
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800515 status_t res = getTorchStatusLocked(cameraId, &status);
516 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700517 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
518 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800519 return;
520 }
521 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800522 return;
523 }
524
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800525 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800526 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800527 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
528 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800529 return;
530 }
531
Ruben Brunkcc776712015-02-17 20:18:47 -0800532 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700533 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700534 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700535 auto iter = mTorchUidMap.find(cameraId);
536 if (iter != mTorchUidMap.end()) {
537 int oldUid = iter->second.second;
538 int newUid = iter->second.first;
539 BatteryNotifier& notifier(BatteryNotifier::getInstance());
540 if (oldUid != newUid) {
541 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800542 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700543 notifier.noteFlashlightOff(cameraId, oldUid);
544 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700546 notifier.noteFlashlightOn(cameraId, newUid);
547 }
548 iter->second.second = newUid;
549 } else {
550 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800551 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700552 notifier.noteFlashlightOn(cameraId, oldUid);
553 } else {
554 notifier.noteFlashlightOff(cameraId, oldUid);
555 }
556 }
557 }
558 }
559
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800560 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800561}
562
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700563static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
564 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
565 checkPermission(sCameraPermission, callingPid, callingUid);
566}
567
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800568Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700569 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100570 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700571 bool hasSystemCameraPermissions =
572 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
573 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700574 switch (type) {
575 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700576 if (hasSystemCameraPermissions) {
577 *numCameras = static_cast<int>(mNormalDeviceIds.size());
578 } else {
579 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800581 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700582 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700583 if (hasSystemCameraPermissions) {
584 *numCameras = mNumberOfCameras;
585 } else {
586 *numCameras = mNumberOfCamerasWithoutSystemCamera;
587 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700589 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800590 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700591 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800592 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
593 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700594 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800595 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596}
597
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800598Status CameraService::getCameraInfo(int cameraId,
599 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700600 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100601 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700602 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
603 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
604 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
605 "characteristics for system only device %s: ", cameraIdStr.c_str());
606 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100607
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800608 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800609 return STATUS_ERROR(ERROR_DISCONNECTED,
610 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700611 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700612 bool hasSystemCameraPermissions =
613 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
614 CameraThreadState::getCallingUid());
615 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
616 if (hasSystemCameraPermissions) {
617 cameraIdBound = mNumberOfCameras;
618 }
619 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800620 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
621 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622 }
623
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800624 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800625 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700626 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100627 if (err != OK) {
628 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
629 "Error retrieving camera info from device %d: %s (%d)", cameraId,
630 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800631 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100632
Ruben Brunkcc776712015-02-17 20:18:47 -0800633 return ret;
634}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700635
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800636std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700637 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
638 auto callingPid = CameraThreadState::getCallingPid();
639 auto callingUid = CameraThreadState::getCallingUid();
640 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
641 getpid() == callingPid) {
642 deviceIds = &mNormalDeviceIds;
643 }
644 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800645 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700646 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800647 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800648 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800649
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700650 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800651}
652
653String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
654 Mutex::Autolock lock(mServiceLock);
655 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800656}
657
658Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800659 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700660 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700661 if (!cameraInfo) {
662 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800663 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700664 }
665
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800666 if (!mInitialized) {
667 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800668 return STATUS_ERROR(ERROR_DISCONNECTED,
669 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700670 }
671
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700672 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
673 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
674 "characteristics for system only device %s: ", String8(cameraId).string());
675 }
676
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800677 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800678
Emilian Peevf53f66e2017-04-11 14:29:43 +0100679 status_t res = mCameraProviderManager->getCameraCharacteristics(
680 String8(cameraId).string(), cameraInfo);
681 if (res != OK) {
682 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
683 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
684 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700685 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700686 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
687 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
688 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
690 "for device %s", String8(cameraId).string());
691 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700692 int callingPid = CameraThreadState::getCallingPid();
693 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100694 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700695 // If it's not calling from cameraserver, check the permission only if
696 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
697 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100698 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700699 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700700 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100701 res = cameraInfo->removePermissionEntries(
702 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
703 &tagsRemoved);
704 if (res != OK) {
705 cameraInfo->clear();
706 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
707 " characteristics needing camera permission for device %s: %s (%d)",
708 String8(cameraId).string(), strerror(-res), res);
709 }
710 }
711
712 if (!tagsRemoved.empty()) {
713 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
714 tagsRemoved.data(), tagsRemoved.size());
715 if (res != OK) {
716 cameraInfo->clear();
717 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
718 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
719 strerror(-res), res);
720 }
721 }
722
Zhijun He2b59be82013-09-25 10:14:30 -0700723 return ret;
724}
725
Ruben Brunkcc776712015-02-17 20:18:47 -0800726String8 CameraService::getFormattedCurrentTime() {
727 time_t now = time(nullptr);
728 char formattedTime[64];
729 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
730 return String8(formattedTime);
731}
732
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733Status CameraService::getCameraVendorTagDescriptor(
734 /*out*/
735 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700736 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800737 if (!mInitialized) {
738 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800740 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800741 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
742 if (globalDescriptor != nullptr) {
743 *desc = *(globalDescriptor.get());
744 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800746}
747
Emilian Peev71c73a22017-03-21 16:35:51 +0000748Status CameraService::getCameraVendorTagCache(
749 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
750 ATRACE_CALL();
751 if (!mInitialized) {
752 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
753 return STATUS_ERROR(ERROR_DISCONNECTED,
754 "Camera subsystem not available");
755 }
756 sp<VendorTagDescriptorCache> globalCache =
757 VendorTagDescriptorCache::getGlobalVendorTagCache();
758 if (globalCache != nullptr) {
759 *cache = *(globalCache.get());
760 }
761 return Status::ok();
762}
763
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800764int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700765 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800766
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800767 int deviceVersion = 0;
768
Emilian Peevf53f66e2017-04-11 14:29:43 +0100769 status_t res;
770 hardware::hidl_version maxVersion{0,0};
771 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
772 &maxVersion);
773 if (res != OK) return -1;
774 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800775
Emilian Peevf53f66e2017-04-11 14:29:43 +0100776 hardware::CameraInfo info;
777 if (facing) {
778 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800779 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100780 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800781 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100782
Igor Murashkin634a5152013-02-20 17:15:11 -0800783 return deviceVersion;
784}
785
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800786Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700787 switch(err) {
788 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800790 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800791 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
792 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800793 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return STATUS_ERROR(ERROR_DISCONNECTED,
795 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700796 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
798 "Camera HAL encountered error %d: %s",
799 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700800 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800801}
802
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800803Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800804 const sp<IInterface>& cameraCb, const String16& packageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900805 const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800806 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
807 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800808 /*out*/sp<BasicClient>* client) {
809
Ruben Brunkcc776712015-02-17 20:18:47 -0800810 if (halVersion < 0 || halVersion == deviceVersion) {
811 // Default path: HAL version is unspecified by caller, create CameraClient
812 // based on device version reported by the HAL.
813 switch(deviceVersion) {
814 case CAMERA_DEVICE_API_VERSION_1_0:
815 if (effectiveApiLevel == API_1) { // Camera1 API route
816 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800817 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800818 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700819 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 } else { // Camera2 API route
821 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800823 "Camera device \"%s\" HAL version %d does not support camera2 API",
824 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800825 }
826 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 case CAMERA_DEVICE_API_VERSION_3_0:
828 case CAMERA_DEVICE_API_VERSION_3_1:
829 case CAMERA_DEVICE_API_VERSION_3_2:
830 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700831 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700832 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800833 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 if (effectiveApiLevel == API_1) { // Camera1 API route
835 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800836 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800837 cameraId, api1CameraId,
838 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700839 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800840 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800841 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
842 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800843 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
844 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800845 }
846 break;
847 default:
848 // Should not be reachable
849 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800850 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800851 "Camera device \"%s\" has unknown HAL version %d",
852 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800853 }
854 } else {
855 // A particular HAL version is requested by caller. Create CameraClient
856 // based on the requested HAL version.
857 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
858 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
859 // Only support higher HAL version device opened as HAL1.0 device.
860 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800861 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800862 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700863 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800864 } else {
865 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
866 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
867 " opened as HAL %x device", halVersion, deviceVersion,
868 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800869 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800870 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
871 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800872 }
873 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800874 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800875}
876
Ruben Brunk6267b532015-04-30 17:44:07 -0700877String8 CameraService::toString(std::set<userid_t> intSet) {
878 String8 s("");
879 bool first = true;
880 for (userid_t i : intSet) {
881 if (first) {
882 s.appendFormat("%d", i);
883 first = false;
884 } else {
885 s.appendFormat(", %d", i);
886 }
887 }
888 return s;
889}
890
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800891int32_t CameraService::mapToInterface(TorchModeStatus status) {
892 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
893 switch (status) {
894 case TorchModeStatus::NOT_AVAILABLE:
895 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
896 break;
897 case TorchModeStatus::AVAILABLE_OFF:
898 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
899 break;
900 case TorchModeStatus::AVAILABLE_ON:
901 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
902 break;
903 default:
904 ALOGW("Unknown new flash status: %d", status);
905 }
906 return serviceStatus;
907}
908
909CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
910 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
911 switch (status) {
912 case CameraDeviceStatus::NOT_PRESENT:
913 serviceStatus = StatusInternal::NOT_PRESENT;
914 break;
915 case CameraDeviceStatus::PRESENT:
916 serviceStatus = StatusInternal::PRESENT;
917 break;
918 case CameraDeviceStatus::ENUMERATING:
919 serviceStatus = StatusInternal::ENUMERATING;
920 break;
921 default:
922 ALOGW("Unknown new HAL device status: %d", status);
923 }
924 return serviceStatus;
925}
926
927int32_t CameraService::mapToInterface(StatusInternal status) {
928 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
929 switch (status) {
930 case StatusInternal::NOT_PRESENT:
931 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
932 break;
933 case StatusInternal::PRESENT:
934 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
935 break;
936 case StatusInternal::ENUMERATING:
937 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
938 break;
939 case StatusInternal::NOT_AVAILABLE:
940 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
941 break;
942 case StatusInternal::UNKNOWN:
943 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
944 break;
945 default:
946 ALOGW("Unknown new internal device status: %d", status);
947 }
948 return serviceStatus;
949}
950
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800951Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700952 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700953
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800954 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800955 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800956 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800957 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800959 sp<ICameraClient>{nullptr}, id, cameraId,
960 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900961 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700962 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800963 ).isOk()) {
964 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700965 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700967}
968
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700970 /*out*/
971 CameraParameters* parameters) {
972
973 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
974
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800975 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700976
977 if (parameters == NULL) {
978 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800979 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700980 }
981
Ruben Brunkcc776712015-02-17 20:18:47 -0800982 String8 id = String8::format("%d", cameraId);
983
984 // Check if we already have parameters
985 {
986 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700987 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800988 auto cameraState = getCameraState(id);
989 if (cameraState == nullptr) {
990 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
992 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800993 }
994 CameraParameters p = cameraState->getShimParams();
995 if (!p.isEmpty()) {
996 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800997 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -0700998 }
999 }
1000
Jayant Chowdhary12361932018-08-27 14:46:13 -07001001 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001002 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001003 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001004 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 // Error already logged by callee
1006 return ret;
1007 }
1008
1009 // Check for parameters again
1010 {
1011 // Scope for service lock
1012 Mutex::Autolock lock(mServiceLock);
1013 auto cameraState = getCameraState(id);
1014 if (cameraState == nullptr) {
1015 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001016 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1017 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001018 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001019 CameraParameters p = cameraState->getShimParams();
1020 if (!p.isEmpty()) {
1021 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001022 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001023 }
1024 }
1025
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1027 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001028 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001029}
1030
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001031// Can camera service trust the caller based on the calling UID?
1032static bool isTrustedCallingUid(uid_t uid) {
1033 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001034 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001035 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001036 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001037 return true;
1038 default:
1039 return false;
1040 }
1041}
1042
Nicholas Sauera3620332019-04-03 14:05:17 -07001043static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1044 PermissionController pc;
1045 uid = pc.getPackageUid(packageName, 0);
1046 if (uid <= 0) {
1047 ALOGE("Unknown package: '%s'", String8(packageName).string());
1048 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1049 return BAD_VALUE;
1050 }
1051
1052 if (userId < 0) {
1053 ALOGE("Invalid user: %d", userId);
1054 dprintf(err, "Invalid user: %d\n", userId);
1055 return BAD_VALUE;
1056 }
1057
1058 uid = multiuser_get_uid(userId, uid);
1059 return NO_ERROR;
1060}
1061
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001062Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001063 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1064 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001065
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001066#ifdef __BRILLO__
1067 UNUSED(clientName8);
1068 UNUSED(clientUid);
1069 UNUSED(clientPid);
1070 UNUSED(originalClientPid);
1071#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001072 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1073 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001074 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001075 return allowed;
1076 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001077#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001078
Jayant Chowdhary12361932018-08-27 14:46:13 -07001079 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001080
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001081 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001082 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1083 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001084 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1085 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001086 }
1087
Ruben Brunkcc776712015-02-17 20:18:47 -08001088 if (getCameraState(cameraId) == nullptr) {
1089 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1090 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001091 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1092 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 }
1094
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001095 status_t err = checkIfDeviceIsUsable(cameraId);
1096 if (err != NO_ERROR) {
1097 switch(err) {
1098 case -ENODEV:
1099 case -EBUSY:
1100 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1101 "No camera device with ID \"%s\" currently available", cameraId.string());
1102 default:
1103 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1104 "Unknown error connecting to ID \"%s\"", cameraId.string());
1105 }
1106 }
1107 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001108}
1109
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001110Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001111 const String8& clientName8, int& clientUid, int& clientPid,
1112 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001113 int callingPid = CameraThreadState::getCallingPid();
1114 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001116 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001118 clientUid = callingUid;
1119 } else if (!isTrustedCallingUid(callingUid)) {
1120 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1121 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001122 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1123 "Untrusted caller (calling PID %d, UID %d) trying to "
1124 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1125 callingPid, callingUid, cameraId.string(),
1126 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
1128
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001129 // Check if we can trust clientPid
1130 if (clientPid == USE_CALLING_PID) {
1131 clientPid = callingPid;
1132 } else if (!isTrustedCallingUid(callingUid)) {
1133 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1134 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001135 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1136 "Untrusted caller (calling PID %d, UID %d) trying to "
1137 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1138 callingPid, callingUid, cameraId.string(),
1139 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001140 }
1141
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001142 if (shouldRejectSystemCameraConnection(cameraId)) {
1143 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1144 cameraId.c_str());
1145 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1146 "available", cameraId.string());
1147 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001148 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1149 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1150 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1151 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1152 "found while trying to query device kind", cameraId.string());
1153
1154 }
1155
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001156 // If it's not calling from cameraserver, check the permission if the
1157 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1158 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001159 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001160 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001161 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001162 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001163 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1164 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1165 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001166 }
1167
Svet Ganova453d0d2018-01-11 15:37:58 -08001168 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001169 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001170 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001171 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1172 clientPid, clientUid);
1173 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001174 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1175 "calling UID %d proc state %" PRId32 ")",
1176 clientName8.string(), clientUid, clientPid, cameraId.string(),
1177 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001178 }
1179
Michael Grooverd1d435a2018-12-18 17:39:42 -08001180 // If sensor privacy is enabled then prevent access to the camera
1181 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1182 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1183 return STATUS_ERROR_FMT(ERROR_DISABLED,
1184 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1185 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1186 }
1187
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001188 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1189 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001190 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001191 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192
Ruben Brunk6267b532015-04-30 17:44:07 -07001193 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001194
Ruben Brunka8ca9152015-04-07 14:23:40 -07001195 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001196 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001197 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001198 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001199 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1200 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1201 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001202 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1203 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1204 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001205 }
1206
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001207 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001208}
1209
1210status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1211 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001212 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001213 if (cameraState == nullptr) {
1214 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1215 cameraId.string());
1216 return -ENODEV;
1217 }
1218
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001219 StatusInternal currentStatus = cameraState->getStatus();
1220 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1222 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001223 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001224 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001225 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1226 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001227 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001228 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001229
Ruben Brunkcc776712015-02-17 20:18:47 -08001230 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001231}
1232
Ruben Brunkcc776712015-02-17 20:18:47 -08001233void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1234 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236 // Make a descriptor for the incoming client
1237 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1238 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1239
1240 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1241 String8(client->getPackageName()));
1242
1243 if (evicted.size() > 0) {
1244 // This should never happen - clients should already have been removed in disconnect
1245 for (auto& i : evicted) {
1246 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1247 __FUNCTION__, i->getKey().string());
1248 }
1249
1250 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1251 __FUNCTION__);
1252 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001253
1254 // And register a death notification for the client callback. Do
1255 // this last to avoid Binder policy where a nested Binder
1256 // transaction might be pre-empted to service the client death
1257 // notification if the client process dies before linkToDeath is
1258 // invoked.
1259 sp<IBinder> remoteCallback = client->getRemote();
1260 if (remoteCallback != nullptr) {
1261 remoteCallback->linkToDeath(this);
1262 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001263}
1264
1265status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1266 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1267 /*out*/
1268 sp<BasicClient>* client,
1269 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001270 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001271 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001272 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001273 DescriptorPtr clientDescriptor;
1274 {
1275 if (effectiveApiLevel == API_1) {
1276 // If we are using API1, any existing client for this camera ID with the same remote
1277 // should be returned rather than evicted to allow MediaRecorder to work properly.
1278
1279 auto current = mActiveClientManager.get(cameraId);
1280 if (current != nullptr) {
1281 auto clientSp = current->getValue();
1282 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001283 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1284 ALOGW("CameraService connect called from same client, but with a different"
1285 " API level, evicting prior client...");
1286 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001287 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001288 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001289 *client = clientSp;
1290 return NO_ERROR;
1291 }
1292 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001293 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001294 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001295
Ruben Brunkcc776712015-02-17 20:18:47 -08001296 // Get current active client PIDs
1297 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1298 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001299
Emilian Peev8131a262017-02-01 12:33:43 +00001300 std::vector<int> priorityScores(ownerPids.size());
1301 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001302
Emilian Peev8131a262017-02-01 12:33:43 +00001303 // Get priority scores of all active PIDs
1304 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1305 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1306 /*out*/&priorityScores[0]);
1307 if (err != OK) {
1308 ALOGE("%s: Priority score query failed: %d",
1309 __FUNCTION__, err);
1310 return err;
1311 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001312
Ruben Brunkcc776712015-02-17 20:18:47 -08001313 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001314 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001315 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001316 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001317 resource_policy::ClientPriority(priorityScores[i], states[i],
1318 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001319 }
1320 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001321
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 // Get state for the given cameraId
1323 auto state = getCameraState(cameraId);
1324 if (state == nullptr) {
1325 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1326 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001327 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001328 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001329 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001330
1331 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001332 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001333 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1334 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001335 priorityScores[priorityScores.size() - 1],
1336 clientPid,
1337 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001338
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001339 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1340
Ruben Brunkcc776712015-02-17 20:18:47 -08001341 // Find clients that would be evicted
1342 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1343
1344 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1345 // background, so we cannot do evictions
1346 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1347 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1348 " priority).", clientPid);
1349
1350 sp<BasicClient> clientSp = clientDescriptor->getValue();
1351 String8 curTime = getFormattedCurrentTime();
1352 auto incompatibleClients =
1353 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1354
1355 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001356 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001357 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001358 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001359
1360 for (auto& i : incompatibleClients) {
1361 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001362 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1363 i->getKey().string(),
1364 String8{i->getValue()->getPackageName()}.string(),
1365 i->getOwnerId(), i->getPriority().getScore(),
1366 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001367 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001368 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001369 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001370 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001371 }
1372
1373 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001374 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 mEventLog.add(msg);
1376
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001377 auto current = mActiveClientManager.get(cameraId);
1378 if (current != nullptr) {
1379 return -EBUSY; // CAMERA_IN_USE
1380 } else {
1381 return -EUSERS; // MAX_CAMERAS_IN_USE
1382 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001383 }
1384
1385 for (auto& i : evicted) {
1386 sp<BasicClient> clientSp = i->getValue();
1387 if (clientSp.get() == nullptr) {
1388 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1389
1390 // TODO: Remove this
1391 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1392 __FUNCTION__);
1393 mActiveClientManager.remove(i);
1394 continue;
1395 }
1396
1397 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1398 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001399 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001400
Ruben Brunkcc776712015-02-17 20:18:47 -08001401 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001402 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001403 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1404 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001405 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001406 i->getOwnerId(), i->getPriority().getScore(),
1407 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001408 packageName.string(), clientPid, clientPriority.getScore(),
1409 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001410
1411 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001414 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001415 }
1416
Ruben Brunkcc776712015-02-17 20:18:47 -08001417 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1418 // other clients from connecting in mServiceLockWrapper if held
1419 mServiceLock.unlock();
1420
1421 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001422 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001423
1424 // Destroy evicted clients
1425 for (auto& i : evictedClients) {
1426 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001427 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001428 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001429
Jayant Chowdhary12361932018-08-27 14:46:13 -07001430 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001431
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001432 for (const auto& i : evictedClients) {
1433 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1434 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1435 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1436 if (ret == TIMED_OUT) {
1437 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1438 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1439 mActiveClientManager.toString().string());
1440 return -EBUSY;
1441 }
1442 if (ret != NO_ERROR) {
1443 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1444 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1445 ret, mActiveClientManager.toString().string());
1446 return ret;
1447 }
1448 }
1449
1450 evictedClients.clear();
1451
Ruben Brunkcc776712015-02-17 20:18:47 -08001452 // Once clients have been disconnected, relock
1453 mServiceLock.lock();
1454
1455 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1456 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1457 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001458 }
1459
Ruben Brunkcc776712015-02-17 20:18:47 -08001460 *partial = clientDescriptor;
1461 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001462}
1463
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001465 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001466 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001467 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001468 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001469 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001470 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001472
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001473 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001474 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001475
1476 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001477 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001478 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001479 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, {},
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001480 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001481
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001483 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001484 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001485 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486 }
1487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001488 *device = client;
1489 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490}
1491
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001492Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001493 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001494 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001495 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001496 int clientUid,
1497 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001498 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001499
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001500 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001501 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001502
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001503 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001504 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001505 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001506 clientPackageName, {}, clientUid, USE_CALLING_PID, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001507 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001508
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001509 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001510 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001511 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001512 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001513 }
1514
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001515 *device = client;
1516 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001517}
1518
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001519bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1520 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001521 // If the client is not a vendor client, don't add listener if
1522 // a) the camera is a publicly hidden secure camera OR
1523 // b) the camera is a system only camera and the client doesn't
1524 // have android.permission.SYSTEM_CAMERA permissions.
1525 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1526 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1527 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001528 return true;
1529 }
1530 return false;
1531}
1532
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001533bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1534 // Rules for rejection:
1535 // 1) If cameraserver tries to access this camera device, accept the
1536 // connection.
1537 // 2) The camera device is a publicly hidden secure camera device AND some
1538 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1539 // reject it.
1540 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1541 // and the serving thread is a non hwbinder thread, the client must have
1542 // android.permission.SYSTEM_CAMERA permissions to connect.
1543
1544 int cPid = CameraThreadState::getCallingPid();
1545 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001546 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1547 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1548 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1549 return true;
1550 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001551
1552 // (1) Cameraserver trying to connect, accept.
1553 if (CameraThreadState::getCallingPid() == getpid()) {
1554 return false;
1555 }
1556 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001557 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001558 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1559 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1560 return true;
1561 }
1562 // (3) Here we only check for permissions if it is a system only camera device. This is since
1563 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1564 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1565 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001566 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001567 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1568 !hasPermissionsForSystemCamera(cPid, cUid)) {
1569 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1570 cameraId.c_str());
1571 return true;
1572 }
1573
1574 return false;
1575}
1576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577Status CameraService::connectDevice(
1578 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001579 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001580 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001581 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001582 int clientUid,
1583 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001585
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001586 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001588 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001590 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001591
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001592 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001593 std::string vendorClient =
1594 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1595 clientPackageNameAdj = String16(vendorClient.c_str());
1596 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001597 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001598 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001599 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001600 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001601
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001603 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001604 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001605 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001606 }
1607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 *device = client;
1609 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001610}
1611
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001612template<class CALLBACK, class CLIENT>
1613Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001614 int api1CameraId, int halVersion, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001615 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001616 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001617 /*out*/sp<CLIENT>& device) {
1618 binder::Status ret = binder::Status::ok();
1619
1620 String8 clientName8(clientPackageName);
1621
1622 int originalClientPid = 0;
1623
1624 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1625 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1626 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1627 static_cast<int>(effectiveApiLevel));
1628
1629 sp<CLIENT> client = nullptr;
1630 {
1631 // Acquire mServiceLock and prevent other clients from connecting
1632 std::unique_ptr<AutoConditionLock> lock =
1633 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1634
1635 if (lock == nullptr) {
1636 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1637 , clientPid);
1638 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1639 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1640 cameraId.string(), clientName8.string(), clientPid);
1641 }
1642
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001643 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001644 if(!(ret = validateConnectLocked(cameraId, clientName8,
1645 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1646 return ret;
1647 }
1648
1649 // Check the shim parameters after acquiring lock, if they have already been updated and
1650 // we were doing a shim update, return immediately
1651 if (shimUpdateOnly) {
1652 auto cameraState = getCameraState(cameraId);
1653 if (cameraState != nullptr) {
1654 if (!cameraState->getShimParams().isEmpty()) return ret;
1655 }
1656 }
1657
1658 status_t err;
1659
1660 sp<BasicClient> clientTmp = nullptr;
1661 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1662 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1663 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1664 /*out*/&partial)) != NO_ERROR) {
1665 switch (err) {
1666 case -ENODEV:
1667 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1668 "No camera device with ID \"%s\" currently available",
1669 cameraId.string());
1670 case -EBUSY:
1671 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1672 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1673 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001674 case -EUSERS:
1675 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1676 "Too many cameras already open, cannot open camera \"%s\"",
1677 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001678 default:
1679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1680 "Unexpected error %s (%d) opening camera \"%s\"",
1681 strerror(-err), err, cameraId.string());
1682 }
1683 }
1684
1685 if (clientTmp.get() != nullptr) {
1686 // Handle special case for API1 MediaRecorder where the existing client is returned
1687 device = static_cast<CLIENT*>(clientTmp.get());
1688 return ret;
1689 }
1690
1691 // give flashlight a chance to close devices if necessary.
1692 mFlashlight->prepareDeviceOpen(cameraId);
1693
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001694 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001695 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001696 if (facing == -1) {
1697 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1698 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1699 "Unable to get camera device \"%s\" facing", cameraId.string());
1700 }
1701
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001702 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001703 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001704 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001705 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001706 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001707 /*out*/&tmp)).isOk()) {
1708 return ret;
1709 }
1710 client = static_cast<CLIENT*>(tmp.get());
1711
1712 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1713 __FUNCTION__);
1714
Emilian Peevbd8c5032018-02-14 23:05:40 +00001715 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001716 if (err != OK) {
1717 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001718 // Errors could be from the HAL module open call or from AppOpsManager
1719 switch(err) {
1720 case BAD_VALUE:
1721 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1722 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1723 case -EBUSY:
1724 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1725 "Camera \"%s\" is already open", cameraId.string());
1726 case -EUSERS:
1727 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1728 "Too many cameras already open, cannot open camera \"%s\"",
1729 cameraId.string());
1730 case PERMISSION_DENIED:
1731 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1732 "No permission to open camera \"%s\"", cameraId.string());
1733 case -EACCES:
1734 return STATUS_ERROR_FMT(ERROR_DISABLED,
1735 "Camera \"%s\" disabled by policy", cameraId.string());
1736 case -ENODEV:
1737 default:
1738 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1739 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1740 strerror(-err), err);
1741 }
1742 }
1743
1744 // Update shim paremeters for legacy clients
1745 if (effectiveApiLevel == API_1) {
1746 // Assume we have always received a Client subclass for API1
1747 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1748 String8 rawParams = shimClient->getParameters();
1749 CameraParameters params(rawParams);
1750
1751 auto cameraState = getCameraState(cameraId);
1752 if (cameraState != nullptr) {
1753 cameraState->setShimParams(params);
1754 } else {
1755 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1756 __FUNCTION__, cameraId.string());
1757 }
1758 }
1759
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001760 // Set rotate-and-crop override behavior
1761 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1762 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1763 }
1764
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001765 if (shimUpdateOnly) {
1766 // If only updating legacy shim parameters, immediately disconnect client
1767 mServiceLock.unlock();
1768 client->disconnect();
1769 mServiceLock.lock();
1770 } else {
1771 // Otherwise, add client to active clients list
1772 finishConnectLocked(client, partial);
1773 }
1774 } // lock is destroyed, allow further connect calls
1775
1776 // Important: release the mutex here so the client can call back into the service from its
1777 // destructor (can be at the end of the call)
1778 device = client;
1779 return ret;
1780}
1781
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001782status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1783 if (offlineClient.get() == nullptr) {
1784 return BAD_VALUE;
1785 }
1786
1787 {
1788 // Acquire mServiceLock and prevent other clients from connecting
1789 std::unique_ptr<AutoConditionLock> lock =
1790 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1791
1792 if (lock == nullptr) {
1793 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1794 , __FUNCTION__, offlineClient->getClientPid());
1795 return TIMED_OUT;
1796 }
1797
1798 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1799 if (onlineClientDesc.get() == nullptr) {
1800 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1801 cameraId.c_str());
1802 return BAD_VALUE;
1803 }
1804
1805 // Offline clients do not evict or conflict with other online devices. Resource sharing
1806 // conflicts are handled by the camera provider which will either succeed or fail before
1807 // reaching this method.
1808 const auto& onlinePriority = onlineClientDesc->getPriority();
1809 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1810 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1811 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1812 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1813
1814 // Allow only one offline device per camera
1815 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1816 if (!incompatibleClients.empty()) {
1817 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1818 return BAD_VALUE;
1819 }
1820
1821 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1822 if (err != OK) {
1823 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1824 return err;
1825 }
1826
1827 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1828 if (evicted.size() > 0) {
1829 for (auto& i : evicted) {
1830 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1831 __FUNCTION__, i->getKey().string());
1832 }
1833
1834 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1835 "properly", __FUNCTION__);
1836
1837 return BAD_VALUE;
1838 }
1839
1840 logConnectedOffline(offlineClientDesc->getKey(),
1841 static_cast<int>(offlineClientDesc->getOwnerId()),
1842 String8(offlineClient->getPackageName()));
1843
1844 sp<IBinder> remoteCallback = offlineClient->getRemote();
1845 if (remoteCallback != nullptr) {
1846 remoteCallback->linkToDeath(this);
1847 }
1848 } // lock is destroyed, allow further connect calls
1849
1850 return OK;
1851}
1852
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001854 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001855 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001856
1857 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001858 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001859 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1861 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001862 }
1863
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001864 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001865 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001866
1867 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 auto state = getCameraState(id);
1869 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001870 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001871 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1872 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 }
1874
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001875 StatusInternal cameraStatus = state->getStatus();
1876 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001877 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1878 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001879 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1880 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001881 }
1882
1883 {
1884 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001885 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001886 status_t err = getTorchStatusLocked(id, &status);
1887 if (err != OK) {
1888 if (err == NAME_NOT_FOUND) {
1889 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1890 "Camera \"%s\" does not have a flash unit", id.string());
1891 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001892 ALOGE("%s: getting current torch status failed for camera %s",
1893 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001894 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1895 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1896 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001897 }
1898
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001899 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001900 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001901 ALOGE("%s: torch mode of camera %s is not available because "
1902 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001903 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1904 "Torch for camera \"%s\" is not available due to an existing camera user",
1905 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001906 } else {
1907 ALOGE("%s: torch mode of camera %s is not available due to "
1908 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001909 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1910 "Torch for camera \"%s\" is not available due to insufficient resources",
1911 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001912 }
1913 }
1914 }
1915
Ruben Brunk99e69712015-05-26 17:25:07 -07001916 {
1917 // Update UID map - this is used in the torch status changed callbacks, so must be done
1918 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001919 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001920 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1921 mTorchUidMap[id].first = uid;
1922 mTorchUidMap[id].second = uid;
1923 } else {
1924 // Set the pending UID
1925 mTorchUidMap[id].first = uid;
1926 }
1927 }
1928
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001929 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001930
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001931 if (err != OK) {
1932 int32_t errorCode;
1933 String8 msg;
1934 switch (err) {
1935 case -ENOSYS:
1936 msg = String8::format("Camera \"%s\" has no flashlight",
1937 id.string());
1938 errorCode = ERROR_ILLEGAL_ARGUMENT;
1939 break;
1940 default:
1941 msg = String8::format(
1942 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1943 id.string(), enabled, strerror(-err), err);
1944 errorCode = ERROR_INVALID_OPERATION;
1945 }
1946 ALOGE("%s: %s", __FUNCTION__, msg.string());
1947 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001948 }
1949
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001950 {
1951 // update the link to client's death
1952 Mutex::Autolock al(mTorchClientMapMutex);
1953 ssize_t index = mTorchClientMap.indexOfKey(id);
1954 if (enabled) {
1955 if (index == NAME_NOT_FOUND) {
1956 mTorchClientMap.add(id, clientBinder);
1957 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001958 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001959 mTorchClientMap.replaceValueAt(index, clientBinder);
1960 }
1961 clientBinder->linkToDeath(this);
1962 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001963 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001964 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001965 }
1966
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001967 int clientPid = CameraThreadState::getCallingPid();
1968 const char *id_cstr = id.c_str();
1969 const char *torchState = enabled ? "on" : "off";
1970 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1971 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001972 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001973}
1974
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001975Status CameraService::notifySystemEvent(int32_t eventId,
1976 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001977 const int pid = CameraThreadState::getCallingPid();
1978 const int selfPid = getpid();
1979
1980 // Permission checks
1981 if (pid != selfPid) {
1982 // Ensure we're being called by system_server, or similar process with
1983 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001984 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001985 const int uid = CameraThreadState::getCallingUid();
1986 ALOGE("Permission Denial: cannot send updates to camera service about system"
1987 " events from pid=%d, uid=%d", pid, uid);
1988 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001989 "No permission to send updates to camera service about system events"
1990 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001991 }
1992 }
1993
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001994 ATRACE_CALL();
1995
Ruben Brunk36597b22015-03-20 22:15:57 -07001996 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001997 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001998 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07001999 // from a system server crash
2000 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002001 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002002 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002003 break;
2004 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002005 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002006 default: {
2007 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2008 eventId);
2009 break;
2010 }
2011 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002012 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002013}
2014
Emilian Peev53722fa2019-02-22 17:47:20 -08002015void CameraService::notifyMonitoredUids() {
2016 Mutex::Autolock lock(mStatusListenerLock);
2017
2018 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002019 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002020 if (!ret.isOk()) {
2021 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2022 ret.exceptionCode());
2023 }
2024 }
2025}
2026
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002027Status CameraService::notifyDeviceStateChange(int64_t newState) {
2028 const int pid = CameraThreadState::getCallingPid();
2029 const int selfPid = getpid();
2030
2031 // Permission checks
2032 if (pid != selfPid) {
2033 // Ensure we're being called by system_server, or similar process with
2034 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002035 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002036 const int uid = CameraThreadState::getCallingUid();
2037 ALOGE("Permission Denial: cannot send updates to camera service about device"
2038 " state changes from pid=%d, uid=%d", pid, uid);
2039 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2040 "No permission to send updates to camera service about device state"
2041 " changes from pid=%d, uid=%d", pid, uid);
2042 }
2043 }
2044
2045 ATRACE_CALL();
2046
2047 using hardware::camera::provider::V2_5::DeviceState;
2048 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2049 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2050 newDeviceState |= DeviceState::BACK_COVERED;
2051 }
2052 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2053 newDeviceState |= DeviceState::FRONT_COVERED;
2054 }
2055 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2056 newDeviceState |= DeviceState::FOLDED;
2057 }
2058 // Only map vendor bits directly
2059 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2060 newDeviceState |= vendorBits;
2061
2062 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2063 Mutex::Autolock l(mServiceLock);
2064 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2065
2066 return Status::ok();
2067}
2068
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002069 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002070 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2071 ATRACE_CALL();
2072 if (!concurrentCameraIds) {
2073 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2074 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2075 }
2076
2077 if (!mInitialized) {
2078 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2079 return STATUS_ERROR(ERROR_DISCONNECTED,
2080 "Camera subsystem is not available");
2081 }
2082 // First call into the provider and get the set of concurrent camera
2083 // combinations
2084 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002085 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002086 for (auto &combination : concurrentCameraCombinations) {
2087 std::vector<std::string> validCombination;
2088 for (auto &cameraId : combination) {
2089 // if the camera state is not present, skip
2090 String8 cameraIdStr(cameraId.c_str());
2091 auto state = getCameraState(cameraIdStr);
2092 if (state == nullptr) {
2093 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2094 continue;
2095 }
2096 StatusInternal status = state->getStatus();
2097 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2098 continue;
2099 }
2100 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2101 continue;
2102 }
2103 validCombination.push_back(cameraId);
2104 }
2105 if (validCombination.size() != 0) {
2106 concurrentCameraIds->push_back(std::move(validCombination));
2107 }
2108 }
2109 return Status::ok();
2110}
2111
2112Status CameraService::isConcurrentSessionConfigurationSupported(
2113 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2114 /*out*/bool* isSupported) {
2115 if (!isSupported) {
2116 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2117 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2118 }
2119
2120 if (!mInitialized) {
2121 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2122 return STATUS_ERROR(ERROR_DISCONNECTED,
2123 "Camera subsystem is not available");
2124 }
2125
2126 // Check for camera permissions
2127 int callingPid = CameraThreadState::getCallingPid();
2128 int callingUid = CameraThreadState::getCallingUid();
2129 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2130 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2131 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2132 "android.permission.CAMERA needed to call"
2133 "isConcurrentSessionConfigurationSupported");
2134 }
2135
2136 status_t res =
2137 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2138 cameraIdsAndSessionConfigurations, isSupported);
2139 if (res != OK) {
2140 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2141 "support %s (%d)", strerror(-res), res);
2142 }
2143 return Status::ok();
2144}
2145
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002146Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2147 /*out*/
2148 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002149 return addListenerHelper(listener, cameraStatuses);
2150}
2151
2152Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2153 /*out*/
2154 std::vector<hardware::CameraStatus> *cameraStatuses,
2155 bool isVendorListener) {
2156
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002157 ATRACE_CALL();
2158
Igor Murashkinbfc99152013-02-27 12:55:20 -08002159 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002160
Ruben Brunk3450ba72015-06-16 11:00:37 -07002161 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002162 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002163 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002164 }
2165
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002166 auto clientUid = CameraThreadState::getCallingUid();
2167 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002168 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2169 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002170
Igor Murashkinbfc99152013-02-27 12:55:20 -08002171 Mutex::Autolock lock(mServiceLock);
2172
Ruben Brunkcc776712015-02-17 20:18:47 -08002173 {
2174 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002175 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002176 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002177 ALOGW("%s: Tried to add listener %p which was already subscribed",
2178 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002181 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002182
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002184 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2185 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002186 auto ret = serviceListener->initialize();
2187 if (ret != NO_ERROR) {
2188 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2189 strerror(-ret), ret);
2190 ALOGE("%s: %s", __FUNCTION__, msg.string());
2191 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2192 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002193 // The listener still needs to be added to the list of listeners, regardless of what
2194 // permissions the listener process has / whether it is a vendor listener. Since it might be
2195 // eligible to listen to other camera ids.
2196 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002197 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002198 }
2199
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002200 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002201 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002202 Mutex::Autolock lock(mCameraStatesLock);
2203 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002204 cameraStatuses->emplace_back(i.first,
2205 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002206 }
2207 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002208 // Remove the camera statuses that should be hidden from the client, we do
2209 // this after collecting the states in order to avoid holding
2210 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2211 // the same time.
2212 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2213 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2214 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2215 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2216 ALOGE("%s: Invalid camera id %s, skipping status update",
2217 __FUNCTION__, s.cameraId.c_str());
2218 return true;
2219 }
2220 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2221 clientUid);}), cameraStatuses->end());
2222
Igor Murashkincba2c162013-03-20 15:56:31 -07002223
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002224 /*
2225 * Immediately signal current torch status to this listener only
2226 * This may be a subset of all the devices, so don't include it in the response directly
2227 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002228 {
2229 Mutex::Autolock al(mTorchStatusMutex);
2230 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002231 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002232 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002233 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002234 }
2235
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002236 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002237}
Ruben Brunkcc776712015-02-17 20:18:47 -08002238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002240 ATRACE_CALL();
2241
Igor Murashkinbfc99152013-02-27 12:55:20 -08002242 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2243
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002244 if (listener == 0) {
2245 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002247 }
2248
Igor Murashkinbfc99152013-02-27 12:55:20 -08002249 Mutex::Autolock lock(mServiceLock);
2250
Ruben Brunkcc776712015-02-17 20:18:47 -08002251 {
2252 Mutex::Autolock lock(mStatusListenerLock);
2253 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002254 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2255 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2256 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002257 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002258 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002259 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002260 }
2261 }
2262
2263 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2264 __FUNCTION__, listener.get());
2265
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002267}
2268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002270
2271 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002272 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2273
2274 if (parameters == NULL) {
2275 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002276 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002277 }
2278
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002280
2281 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002283 // Error logged by caller
2284 return ret;
2285 }
2286
2287 String8 shimParamsString8 = shimParams.flatten();
2288 String16 shimParamsString16 = String16(shimParamsString8);
2289
2290 *parameters = shimParamsString16;
2291
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002293}
2294
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002295Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2296 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002297 ATRACE_CALL();
2298
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002299 const String8 id = String8(cameraId);
2300
2301 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002302
2303 switch (apiVersion) {
2304 case API_VERSION_1:
2305 case API_VERSION_2:
2306 break;
2307 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002308 String8 msg = String8::format("Unknown API version %d", apiVersion);
2309 ALOGE("%s: %s", __FUNCTION__, msg.string());
2310 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002311 }
2312
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002313 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002314 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 case CAMERA_DEVICE_API_VERSION_1_0:
2316 case CAMERA_DEVICE_API_VERSION_3_0:
2317 case CAMERA_DEVICE_API_VERSION_3_1:
2318 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002319 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2320 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002321 *isSupported = false;
2322 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002323 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2324 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002325 *isSupported = true;
2326 }
2327 break;
2328 case CAMERA_DEVICE_API_VERSION_3_2:
2329 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002330 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002331 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002332 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002333 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2334 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 *isSupported = true;
2336 break;
2337 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002338 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002339 ALOGE("%s: %s", __FUNCTION__, msg.string());
2340 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002341 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002343 String8 msg = String8::format("Unknown device version %x for device %s",
2344 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002345 ALOGE("%s: %s", __FUNCTION__, msg.string());
2346 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2347 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002348 }
2349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002351}
2352
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002353Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2354 /*out*/ bool *isSupported) {
2355 ATRACE_CALL();
2356
2357 const String8 id = String8(cameraId);
2358
2359 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2360 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2361
2362 return Status::ok();
2363}
2364
Ruben Brunkcc776712015-02-17 20:18:47 -08002365void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002366 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002367 for (auto& i : mActiveClientManager.getAll()) {
2368 auto clientSp = i->getValue();
2369 if (clientSp.get() == client) {
2370 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002371 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002372 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002373 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002374}
2375
Ruben Brunkcc776712015-02-17 20:18:47 -08002376bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 bool ret = false;
2378 {
2379 // Acquire mServiceLock and prevent other clients from connecting
2380 std::unique_ptr<AutoConditionLock> lock =
2381 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002382
Igor Murashkin634a5152013-02-20 17:15:11 -08002383
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 std::vector<sp<BasicClient>> evicted;
2385 for (auto& i : mActiveClientManager.getAll()) {
2386 auto clientSp = i->getValue();
2387 if (clientSp.get() == nullptr) {
2388 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2389 mActiveClientManager.remove(i);
2390 continue;
2391 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002392 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002393 mActiveClientManager.remove(i);
2394 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002395
Ruben Brunkcc776712015-02-17 20:18:47 -08002396 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002397 clientSp->notifyError(
2398 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002399 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002400 }
2401 }
2402
Ruben Brunkcc776712015-02-17 20:18:47 -08002403 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2404 // other clients from connecting in mServiceLockWrapper if held
2405 mServiceLock.unlock();
2406
Ruben Brunk36597b22015-03-20 22:15:57 -07002407 // Do not clear caller identity, remote caller should be client proccess
2408
Ruben Brunkcc776712015-02-17 20:18:47 -08002409 for (auto& i : evicted) {
2410 if (i.get() != nullptr) {
2411 i->disconnect();
2412 ret = true;
2413 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002414 }
2415
Ruben Brunkcc776712015-02-17 20:18:47 -08002416 // Reacquire mServiceLock
2417 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002418
Ruben Brunkcc776712015-02-17 20:18:47 -08002419 } // lock is destroyed, allow further connect calls
2420
2421 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002422}
2423
Ruben Brunkcc776712015-02-17 20:18:47 -08002424std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2425 const String8& cameraId) const {
2426 std::shared_ptr<CameraState> state;
2427 {
2428 Mutex::Autolock lock(mCameraStatesLock);
2429 auto iter = mCameraStates.find(cameraId);
2430 if (iter != mCameraStates.end()) {
2431 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002434 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435}
2436
Ruben Brunkcc776712015-02-17 20:18:47 -08002437sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2438 // Remove from active clients list
2439 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2440 if (clientDescriptorPtr == nullptr) {
2441 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2442 cameraId.string());
2443 return sp<BasicClient>{nullptr};
2444 }
2445
2446 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002447}
2448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002449void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002450 // Acquire mServiceLock and prevent other clients from connecting
2451 std::unique_ptr<AutoConditionLock> lock =
2452 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2453
Ruben Brunk6267b532015-04-30 17:44:07 -07002454 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002455 for (size_t i = 0; i < newUserIds.size(); i++) {
2456 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002457 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002459 return;
2460 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002462 }
2463
Ruben Brunka8ca9152015-04-07 14:23:40 -07002464
Ruben Brunk6267b532015-04-30 17:44:07 -07002465 if (newAllowedUsers == mAllowedUsers) {
2466 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2467 return;
2468 }
2469
2470 logUserSwitch(mAllowedUsers, newAllowedUsers);
2471
2472 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002473
2474 // Current user has switched, evict all current clients.
2475 std::vector<sp<BasicClient>> evicted;
2476 for (auto& i : mActiveClientManager.getAll()) {
2477 auto clientSp = i->getValue();
2478
2479 if (clientSp.get() == nullptr) {
2480 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2481 continue;
2482 }
2483
Ruben Brunk6267b532015-04-30 17:44:07 -07002484 // Don't evict clients that are still allowed.
2485 uid_t clientUid = clientSp->getClientUid();
2486 userid_t clientUserId = multiuser_get_user_id(clientUid);
2487 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2488 continue;
2489 }
2490
Ruben Brunk36597b22015-03-20 22:15:57 -07002491 evicted.push_back(clientSp);
2492
2493 String8 curTime = getFormattedCurrentTime();
2494
2495 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2496 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002497
Ruben Brunk36597b22015-03-20 22:15:57 -07002498 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002499 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002500 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2501 " to user switch.", i->getKey().string(),
2502 String8{clientSp->getPackageName()}.string(),
2503 i->getOwnerId(), i->getPriority().getScore(),
2504 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002505
2506 }
2507
2508 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2509 // blocking other clients from connecting in mServiceLockWrapper if held.
2510 mServiceLock.unlock();
2511
2512 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002513 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002514
2515 for (auto& i : evicted) {
2516 i->disconnect();
2517 }
2518
Jayant Chowdhary12361932018-08-27 14:46:13 -07002519 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002520
2521 // Reacquire mServiceLock
2522 mServiceLock.lock();
2523}
Ruben Brunkcc776712015-02-17 20:18:47 -08002524
Ruben Brunka8ca9152015-04-07 14:23:40 -07002525void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002526 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002527 Mutex::Autolock l(mLogLock);
2528 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529}
2530
Ruben Brunka8ca9152015-04-07 14:23:40 -07002531void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002532 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002533 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002534 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002535 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002536}
2537
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002538void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2539 const char* clientPackage) {
2540 // Log the clients evicted
2541 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2542 cameraId, clientPackage, clientPid));
2543}
2544
Ruben Brunka8ca9152015-04-07 14:23:40 -07002545void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002546 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002547 // Log the clients evicted
2548 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002549 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002550}
2551
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002552void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2553 const char* clientPackage) {
2554 // Log the clients evicted
2555 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2556 clientPackage, clientPid));
2557}
2558
Ruben Brunka8ca9152015-04-07 14:23:40 -07002559void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002560 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002561 // Log the client rejected
2562 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002563 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002564}
2565
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002566void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2567 // Log torch event
2568 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2569 torchState, clientPid));
2570}
2571
Ruben Brunk6267b532015-04-30 17:44:07 -07002572void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2573 const std::set<userid_t>& newUserIds) {
2574 String8 newUsers = toString(newUserIds);
2575 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002576 if (oldUsers.size() == 0) {
2577 oldUsers = "<None>";
2578 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002579 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002580 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002581 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002582}
2583
2584void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2585 // Log the device removal
2586 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2587}
2588
2589void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2590 // Log the device removal
2591 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2592}
2593
2594void CameraService::logClientDied(int clientPid, const char* reason) {
2595 // Log the device removal
2596 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002597}
2598
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002599void CameraService::logServiceError(const char* msg, int errorCode) {
2600 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002601 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002602}
2603
Ruben Brunk36597b22015-03-20 22:15:57 -07002604status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2605 uint32_t flags) {
2606
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 // Permission checks
2608 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002609 case SHELL_COMMAND_TRANSACTION: {
2610 int in = data.readFileDescriptor();
2611 int out = data.readFileDescriptor();
2612 int err = data.readFileDescriptor();
2613 int argc = data.readInt32();
2614 Vector<String16> args;
2615 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2616 args.add(data.readString16());
2617 }
2618 sp<IBinder> unusedCallback;
2619 sp<IResultReceiver> resultReceiver;
2620 status_t status;
2621 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2622 return status;
2623 }
2624 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2625 return status;
2626 }
2627 status = shellCommand(in, out, err, args);
2628 if (resultReceiver != nullptr) {
2629 resultReceiver->send(status);
2630 }
2631 return NO_ERROR;
2632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 }
2634
2635 return BnCameraService::onTransact(code, data, reply, flags);
2636}
2637
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638// We share the media players for shutter and recording sound for all clients.
2639// A reference count is kept to determine when we will actually release the
2640// media players.
2641
Jaekyun Seokef498052018-03-23 13:09:44 +09002642sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2643 sp<MediaPlayer> mp = new MediaPlayer();
2644 status_t error;
2645 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002646 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002647 error = mp->prepare();
2648 }
2649 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002650 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002651 mp->disconnect();
2652 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002653 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 }
2655 return mp;
2656}
2657
username5755fea2018-12-27 09:48:08 +08002658void CameraService::increaseSoundRef() {
2659 Mutex::Autolock lock(mSoundLock);
2660 mSoundRef++;
2661}
2662
2663void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002664 ATRACE_CALL();
2665
username5755fea2018-12-27 09:48:08 +08002666 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2667 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2668 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2669 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2670 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2671 }
2672 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2673 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2674 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2675 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002676 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002677 }
2678 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2679 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2680 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2681 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2682 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684}
2685
username5755fea2018-12-27 09:48:08 +08002686void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002688 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 if (--mSoundRef) return;
2690
2691 for (int i = 0; i < NUM_SOUNDS; i++) {
2692 if (mSoundPlayer[i] != 0) {
2693 mSoundPlayer[i]->disconnect();
2694 mSoundPlayer[i].clear();
2695 }
2696 }
2697}
2698
2699void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002700 ATRACE_CALL();
2701
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 LOG1("playSound(%d)", kind);
2703 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002704 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 sp<MediaPlayer> player = mSoundPlayer[kind];
2706 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002707 player->seekTo(0);
2708 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 }
2710}
2711
2712// ----------------------------------------------------------------------------
2713
2714CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002715 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002716 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002717 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002718 const String8& cameraIdStr,
2719 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002720 int clientPid, uid_t clientUid,
2721 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002722 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002723 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002724 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002725 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002726 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002727 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002728 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002729{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002730 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002731 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002733 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734
username5755fea2018-12-27 09:48:08 +08002735 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002736
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002737 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738}
2739
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740// tear down the client
2741CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002742 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002743 mDestructionStarted = true;
2744
username5755fea2018-12-27 09:48:08 +08002745 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002746 // unconditionally disconnect. function is idempotent
2747 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748}
2749
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002750sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2751
Igor Murashkin634a5152013-02-20 17:15:11 -08002752CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002753 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002754 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002755 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002756 int clientPid, uid_t clientUid,
2757 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002758 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002759 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002760 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002761 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002762 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002763 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002764 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002765{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002766 if (sCameraService == nullptr) {
2767 sCameraService = cameraService;
2768 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002769 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002770 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002771
2772 // In some cases the calling code has no access to the package it runs under.
2773 // For example, NDK camera API.
2774 // In this case we will get the packages for the calling UID and pick the first one
2775 // for attributing the app op. This will work correctly for runtime permissions
2776 // as for legacy apps we will toggle the app op for all packages in the UID.
2777 // The caveat is that the operation may be attributed to the wrong package and
2778 // stats based on app ops may be slightly off.
2779 if (mClientPackageName.size() <= 0) {
2780 sp<IServiceManager> sm = defaultServiceManager();
2781 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2782 if (binder == 0) {
2783 ALOGE("Cannot get permission service");
2784 // Leave mClientPackageName unchanged (empty) and the further interaction
2785 // with camera will fail in BasicClient::startCameraOps
2786 return;
2787 }
2788
2789 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2790 Vector<String16> packages;
2791
2792 permCtrl->getPackagesForUid(mClientUid, packages);
2793
2794 if (packages.isEmpty()) {
2795 ALOGE("No packages for calling UID");
2796 // Leave mClientPackageName unchanged (empty) and the further interaction
2797 // with camera will fail in BasicClient::startCameraOps
2798 return;
2799 }
2800 mClientPackageName = packages[0];
2801 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002802 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002803 mAppOpsManager = std::make_unique<AppOpsManager>();
2804 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002805
2806 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002807}
2808
2809CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002810 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002811 mDestructionStarted = true;
2812}
2813
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002814binder::Status CameraService::BasicClient::disconnect() {
2815 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002816 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002817 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002818 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002819 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002820
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002821 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002822 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002823 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2824 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002825
2826 sp<IBinder> remote = getRemote();
2827 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002828 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002829 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002830
2831 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002832 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002833 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2834 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2835 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002836
Igor Murashkincba2c162013-03-20 15:56:31 -07002837 // client shouldn't be able to call into us anymore
2838 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002839
2840 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002841}
2842
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002843status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2844 // No dumping of clients directly over Binder,
2845 // must go through CameraService::dump
2846 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002847 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002848 return OK;
2849}
2850
Ruben Brunkcc776712015-02-17 20:18:47 -08002851String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002852 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002853}
2854
2855
2856int CameraService::BasicClient::getClientPid() const {
2857 return mClientPid;
2858}
2859
Ruben Brunk6267b532015-04-30 17:44:07 -07002860uid_t CameraService::BasicClient::getClientUid() const {
2861 return mClientUid;
2862}
2863
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002864bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2865 // Defaults to API2.
2866 return level == API_2;
2867}
2868
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002869status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002870 {
2871 Mutex::Autolock l(mAudioRestrictionLock);
2872 mAudioRestriction = mode;
2873 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002874 sCameraService->updateAudioRestriction();
2875 return OK;
2876}
2877
2878int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002879 return sCameraService->updateAudioRestriction();
2880}
2881
2882int32_t CameraService::BasicClient::getAudioRestriction() const {
2883 Mutex::Autolock l(mAudioRestrictionLock);
2884 return mAudioRestriction;
2885}
2886
2887bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2888 switch (mode) {
2889 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2890 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2891 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2892 return true;
2893 default:
2894 return false;
2895 }
2896}
2897
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002898status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002899 ATRACE_CALL();
2900
Igor Murashkine6800ce2013-03-04 17:25:57 -08002901 {
2902 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002903 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002904 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002905 if (mAppOpsManager != nullptr) {
2906 // Notify app ops that the camera is not available
2907 mOpsCallback = new OpsCallback(this);
2908 int32_t res;
2909 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2910 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002911 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2912 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2913 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002914
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002915 if (res == AppOpsManager::MODE_ERRORED) {
2916 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2917 mCameraIdStr.string(), String8(mClientPackageName).string());
2918 return PERMISSION_DENIED;
2919 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002920
Shuzhen Wang2c656792020-04-13 17:36:49 -07002921 // If the calling Uid is trusted (a native service), the AppOpsManager could
2922 // return MODE_IGNORED. Do not treat such case as error.
2923 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002924 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2925 mCameraIdStr.string(), String8(mClientPackageName).string());
2926 // Return the same error as for device policy manager rejection
2927 return -EACCES;
2928 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002929 }
2930
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002931 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002932
2933 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002934 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002935
Emilian Peev573291c2018-02-10 02:10:56 +00002936 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2937 if (canCastToApiClient(API_2)) {
2938 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2939 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002940 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002941 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002942 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002943
Emilian Peev53722fa2019-02-22 17:47:20 -08002944 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2945
Shuzhen Wang695044d2020-03-06 09:02:23 -08002946 // Notify listeners of camera open/close status
2947 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2948
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002949 return OK;
2950}
2951
2952status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002953 ATRACE_CALL();
2954
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002955 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002956 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002957 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002958 if (mAppOpsManager != nullptr) {
2959 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002960 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002961 mOpsActive = false;
2962 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002963 // This function is called when a client disconnects. This should
2964 // release the camera, but actually only if it was in a proper
2965 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002966 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002967 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002968
Ruben Brunkcc776712015-02-17 20:18:47 -08002969 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002970 sCameraService->updateStatus(StatusInternal::PRESENT,
2971 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002972
Emilian Peev573291c2018-02-10 02:10:56 +00002973 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2974 if (canCastToApiClient(API_2)) {
2975 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2976 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002977 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002978 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002979 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002980 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002981 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002982 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2983 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002984 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002985 mOpsCallback.clear();
2986
Emilian Peev53722fa2019-02-22 17:47:20 -08002987 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2988
Shuzhen Wang695044d2020-03-06 09:02:23 -08002989 // Notify listeners of camera open/close status
2990 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2991
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002992 return OK;
2993}
2994
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002995void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002996 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002997 if (mAppOpsManager == nullptr) {
2998 return;
2999 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003000 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003001 if (op != AppOpsManager::OP_CAMERA) {
3002 ALOGW("Unexpected app ops notification received: %d", op);
3003 return;
3004 }
3005
3006 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003007 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003008 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003009 ALOGV("checkOp returns: %d, %s ", res,
3010 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3011 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3012 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3013 "UNKNOWN");
3014
3015 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003016 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003017 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003018 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003019 }
3020}
3021
Svet Ganova453d0d2018-01-11 15:37:58 -08003022void CameraService::BasicClient::block() {
3023 ATRACE_CALL();
3024
3025 // Reset the client PID to allow server-initiated disconnect,
3026 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003027 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003028 CaptureResultExtras resultExtras; // a dummy result (invalid)
3029 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3030 disconnect();
3031}
3032
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033// ----------------------------------------------------------------------------
3034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003035void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003036 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003037 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003038 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003039 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3040 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3041 api1ErrorCode = CAMERA_ERROR_DISABLED;
3042 }
3043 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003044 } else {
3045 ALOGE("mRemoteCallback is NULL!!");
3046 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003047}
3048
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003049// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003050binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003051 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003052 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003053}
3054
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003055bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3056 return level == API_1;
3057}
3058
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003059CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3060 mClient(client) {
3061}
3062
3063void CameraService::Client::OpsCallback::opChanged(int32_t op,
3064 const String16& packageName) {
3065 sp<BasicClient> client = mClient.promote();
3066 if (client != NULL) {
3067 client->opChanged(op, packageName);
3068 }
3069}
3070
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003072// UidPolicy
3073// ----------------------------------------------------------------------------
3074
3075void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003076 Mutex::Autolock _l(mUidLock);
3077
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003078 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003079 status_t res = mAm.linkToDeath(this);
3080 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003081 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003082 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003083 ActivityManager::PROCESS_STATE_UNKNOWN,
3084 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003085 if (res == OK) {
3086 mRegistered = true;
3087 ALOGV("UidPolicy: Registered with ActivityManager");
3088 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003089}
3090
3091void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003092 Mutex::Autolock _l(mUidLock);
3093
Steven Moreland2f348142019-07-02 15:59:07 -07003094 mAm.unregisterUidObserver(this);
3095 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003096 mRegistered = false;
3097 mActiveUids.clear();
3098 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003099}
3100
3101void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3102 onUidIdle(uid, disabled);
3103}
3104
3105void CameraService::UidPolicy::onUidActive(uid_t uid) {
3106 Mutex::Autolock _l(mUidLock);
3107 mActiveUids.insert(uid);
3108}
3109
3110void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3111 bool deleted = false;
3112 {
3113 Mutex::Autolock _l(mUidLock);
3114 if (mActiveUids.erase(uid) > 0) {
3115 deleted = true;
3116 }
3117 }
3118 if (deleted) {
3119 sp<CameraService> service = mService.promote();
3120 if (service != nullptr) {
3121 service->blockClientsForUid(uid);
3122 }
3123 }
3124}
3125
Emilian Peev53722fa2019-02-22 17:47:20 -08003126void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003127 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003128 bool procStateChange = false;
3129 {
3130 Mutex::Autolock _l(mUidLock);
3131 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3132 (mMonitoredUids[uid].first != procState)) {
3133 mMonitoredUids[uid].first = procState;
3134 procStateChange = true;
3135 }
3136 }
3137
3138 if (procStateChange) {
3139 sp<CameraService> service = mService.promote();
3140 if (service != nullptr) {
3141 service->notifyMonitoredUids();
3142 }
3143 }
3144}
3145
3146void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3147 Mutex::Autolock _l(mUidLock);
3148 auto it = mMonitoredUids.find(uid);
3149 if (it != mMonitoredUids.end()) {
3150 it->second.second++;
3151 } else {
3152 mMonitoredUids.emplace(
3153 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3154 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3155 }
3156}
3157
3158void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3159 Mutex::Autolock _l(mUidLock);
3160 auto it = mMonitoredUids.find(uid);
3161 if (it != mMonitoredUids.end()) {
3162 it->second.second--;
3163 if (it->second.second == 0) {
3164 mMonitoredUids.erase(it);
3165 }
3166 } else {
3167 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3168 }
3169}
3170
Svet Ganov7b4ab782018-03-25 12:48:10 -07003171bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003172 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003173 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003174}
3175
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003176static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3177static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003178
Svet Ganov7b4ab782018-03-25 12:48:10 -07003179bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003180 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003181 // If activity manager is unreachable, assume everything is active
3182 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003183 return true;
3184 }
3185 auto it = mOverrideUids.find(uid);
3186 if (it != mOverrideUids.end()) {
3187 return it->second;
3188 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003189 bool active = mActiveUids.find(uid) != mActiveUids.end();
3190 if (!active) {
3191 // We want active UIDs to always access camera with their first attempt since
3192 // there is no guarantee the app is robustly written and would retry getting
3193 // the camera on failure. The inverse case is not a problem as we would take
3194 // camera away soon once we get the callback that the uid is no longer active.
3195 ActivityManager am;
3196 // Okay to access with a lock held as UID changes are dispatched without
3197 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003198 int64_t startTimeMillis = 0;
3199 do {
3200 // TODO: Fix this b/109950150!
3201 // Okay this is a hack. There is a race between the UID turning active and
3202 // activity being resumed. The proper fix is very risky, so we temporary add
3203 // some polling which should happen pretty rarely anyway as the race is hard
3204 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003205 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003206 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003207 if (active) {
3208 break;
3209 }
3210 if (startTimeMillis <= 0) {
3211 startTimeMillis = uptimeMillis();
3212 }
3213 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003214 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003215 if (remainingTimeMillis <= 0) {
3216 break;
3217 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003218 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3219
3220 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003221 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003222 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003223 } while (true);
3224
Svet Ganov7b4ab782018-03-25 12:48:10 -07003225 if (active) {
3226 // Now that we found out the UID is actually active, cache that
3227 mActiveUids.insert(uid);
3228 }
3229 }
3230 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003231}
3232
Varun Shahb42f1eb2019-04-16 14:45:13 -07003233int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3234 Mutex::Autolock _l(mUidLock);
3235 return getProcStateLocked(uid);
3236}
3237
3238int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3239 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3240 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3241 procState = mMonitoredUids[uid].first;
3242 }
3243 return procState;
3244}
3245
Svet Ganov7b4ab782018-03-25 12:48:10 -07003246void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3247 String16 callingPackage, bool active) {
3248 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003249}
3250
Svet Ganov7b4ab782018-03-25 12:48:10 -07003251void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3252 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003253}
3254
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003255void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3256 Mutex::Autolock _l(mUidLock);
3257 ALOGV("UidPolicy: ActivityManager has died");
3258 mRegistered = false;
3259 mActiveUids.clear();
3260}
3261
Svet Ganov7b4ab782018-03-25 12:48:10 -07003262void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3263 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003264 bool wasActive = false;
3265 bool isActive = false;
3266 {
3267 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003268 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003269 mOverrideUids.erase(uid);
3270 if (insert) {
3271 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3272 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003273 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003274 }
3275 if (wasActive != isActive && !isActive) {
3276 sp<CameraService> service = mService.promote();
3277 if (service != nullptr) {
3278 service->blockClientsForUid(uid);
3279 }
3280 }
3281}
3282
3283// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003284// SensorPrivacyPolicy
3285// ----------------------------------------------------------------------------
3286void CameraService::SensorPrivacyPolicy::registerSelf() {
3287 Mutex::Autolock _l(mSensorPrivacyLock);
3288 if (mRegistered) {
3289 return;
3290 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003291 mSpm.addSensorPrivacyListener(this);
3292 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3293 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003294 if (res == OK) {
3295 mRegistered = true;
3296 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3297 }
3298}
3299
3300void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3301 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003302 mSpm.removeSensorPrivacyListener(this);
3303 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003304 mRegistered = false;
3305 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3306}
3307
3308bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3309 Mutex::Autolock _l(mSensorPrivacyLock);
3310 return mSensorPrivacyEnabled;
3311}
3312
3313binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3314 {
3315 Mutex::Autolock _l(mSensorPrivacyLock);
3316 mSensorPrivacyEnabled = enabled;
3317 }
3318 // if sensor privacy is enabled then block all clients from accessing the camera
3319 if (enabled) {
3320 sp<CameraService> service = mService.promote();
3321 if (service != nullptr) {
3322 service->blockAllClients();
3323 }
3324 }
3325 return binder::Status::ok();
3326}
3327
3328void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3329 Mutex::Autolock _l(mSensorPrivacyLock);
3330 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3331 mRegistered = false;
3332}
3333
3334// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003335// CameraState
3336// ----------------------------------------------------------------------------
3337
3338CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003339 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3340 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3341 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003342
3343CameraService::CameraState::~CameraState() {}
3344
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003345CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003346 Mutex::Autolock lock(mStatusLock);
3347 return mStatus;
3348}
3349
Shuzhen Wang43858162020-01-10 13:42:15 -08003350std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3351 Mutex::Autolock lock(mStatusLock);
3352 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3353 return res;
3354}
3355
Ruben Brunkcc776712015-02-17 20:18:47 -08003356CameraParameters CameraService::CameraState::getShimParams() const {
3357 return mShimParams;
3358}
3359
3360void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3361 mShimParams = params;
3362}
3363
3364int CameraService::CameraState::getCost() const {
3365 return mCost;
3366}
3367
3368std::set<String8> CameraService::CameraState::getConflicting() const {
3369 return mConflicting;
3370}
3371
3372String8 CameraService::CameraState::getId() const {
3373 return mId;
3374}
3375
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003376SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3377 return mSystemCameraKind;
3378}
3379
Shuzhen Wang43858162020-01-10 13:42:15 -08003380bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3381 Mutex::Autolock lock(mStatusLock);
3382 auto result = mUnavailablePhysicalIds.insert(physicalId);
3383 return result.second;
3384}
3385
3386bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3387 Mutex::Autolock lock(mStatusLock);
3388 auto count = mUnavailablePhysicalIds.erase(physicalId);
3389 return count > 0;
3390}
3391
Ruben Brunkcc776712015-02-17 20:18:47 -08003392// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003393// ClientEventListener
3394// ----------------------------------------------------------------------------
3395
3396void CameraService::ClientEventListener::onClientAdded(
3397 const resource_policy::ClientDescriptor<String8,
3398 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003399 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003400 if (basicClient.get() != nullptr) {
3401 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3402 notifier.noteStartCamera(descriptor.getKey(),
3403 static_cast<int>(basicClient->getClientUid()));
3404 }
3405}
3406
3407void CameraService::ClientEventListener::onClientRemoved(
3408 const resource_policy::ClientDescriptor<String8,
3409 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003410 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003411 if (basicClient.get() != nullptr) {
3412 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3413 notifier.noteStopCamera(descriptor.getKey(),
3414 static_cast<int>(basicClient->getClientUid()));
3415 }
3416}
3417
3418
3419// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003420// CameraClientManager
3421// ----------------------------------------------------------------------------
3422
Ruben Brunk99e69712015-05-26 17:25:07 -07003423CameraService::CameraClientManager::CameraClientManager() {
3424 setListener(std::make_shared<ClientEventListener>());
3425}
3426
Ruben Brunkcc776712015-02-17 20:18:47 -08003427CameraService::CameraClientManager::~CameraClientManager() {}
3428
3429sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3430 const String8& id) const {
3431 auto descriptor = get(id);
3432 if (descriptor == nullptr) {
3433 return sp<BasicClient>{nullptr};
3434 }
3435 return descriptor->getValue();
3436}
3437
3438String8 CameraService::CameraClientManager::toString() const {
3439 auto all = getAll();
3440 String8 ret("[");
3441 bool hasAny = false;
3442 for (auto& i : all) {
3443 hasAny = true;
3444 String8 key = i->getKey();
3445 int32_t cost = i->getCost();
3446 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003447 int32_t score = i->getPriority().getScore();
3448 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003449 auto conflicting = i->getConflicting();
3450 auto clientSp = i->getValue();
3451 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003452 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003453 if (clientSp.get() != nullptr) {
3454 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003455 uid_t clientUid = clientSp->getClientUid();
3456 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003457 }
Emilian Peev8131a262017-02-01 12:33:43 +00003458 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3459 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003460
Ruben Brunk6267b532015-04-30 17:44:07 -07003461 if (clientSp.get() != nullptr) {
3462 ret.appendFormat("User Id: %d, ", clientUserId);
3463 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003464 if (packageName.size() != 0) {
3465 ret.appendFormat("Client Package Name: %s", packageName.string());
3466 }
3467
3468 ret.append(", Conflicting Client Devices: {");
3469 for (auto& j : conflicting) {
3470 ret.appendFormat("%s, ", j.string());
3471 }
3472 ret.append("})");
3473 }
3474 if (hasAny) ret.append("\n");
3475 ret.append("]\n");
3476 return ret;
3477}
3478
3479CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3480 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003481 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3482 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003483
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003484 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003485 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3486 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3487
Ruben Brunkcc776712015-02-17 20:18:47 -08003488 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003489 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003490}
3491
3492CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3493 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3494 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003495 partial->getConflicting(), partial->getPriority().getScore(),
3496 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003497}
3498
3499// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500
3501static const int kDumpLockRetries = 50;
3502static const int kDumpLockSleep = 60000;
3503
3504static bool tryLock(Mutex& mutex)
3505{
3506 bool locked = false;
3507 for (int i = 0; i < kDumpLockRetries; ++i) {
3508 if (mutex.tryLock() == NO_ERROR) {
3509 locked = true;
3510 break;
3511 }
3512 usleep(kDumpLockSleep);
3513 }
3514 return locked;
3515}
3516
3517status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003518 ATRACE_CALL();
3519
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003520 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003521 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003522 CameraThreadState::getCallingPid(),
3523 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003524 return NO_ERROR;
3525 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003526 bool locked = tryLock(mServiceLock);
3527 // failed to lock - CameraService is probably deadlocked
3528 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003529 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003530 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003531
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003532 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003533 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003534
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003535 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003536 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003537
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003538 if (locked) mServiceLock.unlock();
3539 return NO_ERROR;
3540 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003541 dprintf(fd, "\n== Service global info: ==\n\n");
3542 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003543 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003544 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3545 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003546 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3547 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3548 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003549 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003550 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3551 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003552
3553 dumpEventLog(fd);
3554
3555 bool stateLocked = tryLock(mCameraStatesLock);
3556 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003557 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003558 }
3559
Emilian Peevbd8c5032018-02-14 23:05:40 +00003560 int argSize = args.size();
3561 for (int i = 0; i < argSize; i++) {
3562 if (args[i] == TagMonitor::kMonitorOption) {
3563 if (i + 1 < argSize) {
3564 mMonitorTags = String8(args[i + 1]);
3565 }
3566 break;
3567 }
3568 }
3569
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003570 for (auto& state : mCameraStates) {
3571 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003572
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003573 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003574
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003575 CameraParameters p = state.second->getShimParams();
3576 if (!p.isEmpty()) {
3577 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3578 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003579 }
3580
3581 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003582 if (clientDescriptor != nullptr) {
3583 dprintf(fd, " Device %s is open. Client instance dump:\n",
3584 cameraId.string());
3585 dprintf(fd, " Client priority score: %d state: %d\n",
3586 clientDescriptor->getPriority().getScore(),
3587 clientDescriptor->getPriority().getState());
3588 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3589
3590 auto client = clientDescriptor->getValue();
3591 dprintf(fd, " Client package: %s\n",
3592 String8(client->getPackageName()).string());
3593
3594 client->dumpClient(fd, args);
3595 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003596 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003597 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003598 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003599
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003600 }
3601
3602 if (stateLocked) mCameraStatesLock.unlock();
3603
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003604 if (locked) mServiceLock.unlock();
3605
Emilian Peevf53f66e2017-04-11 14:29:43 +01003606 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003607
3608 dprintf(fd, "\n== Vendor tags: ==\n\n");
3609
3610 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3611 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003612 sp<VendorTagDescriptorCache> cache =
3613 VendorTagDescriptorCache::getGlobalVendorTagCache();
3614 if (cache == NULL) {
3615 dprintf(fd, "No vendor tags.\n");
3616 } else {
3617 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3618 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003619 } else {
3620 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3621 }
3622
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003623 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003624 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003625 camera3::CameraTraces::dump(fd, args);
3626
3627 // Process dump arguments, if any
3628 int n = args.size();
3629 String16 verboseOption("-v");
3630 String16 unreachableOption("--unreachable");
3631 for (int i = 0; i < n; i++) {
3632 if (args[i] == verboseOption) {
3633 // change logging level
3634 if (i + 1 >= n) continue;
3635 String8 levelStr(args[i+1]);
3636 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003637 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003638 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003639 } else if (args[i] == unreachableOption) {
3640 // Dump memory analysis
3641 // TODO - should limit be an argument parameter?
3642 UnreachableMemoryInfo info;
3643 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3644 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003645 dprintf(fd, "\n== Unable to dump unreachable memory. "
3646 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003647 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003648 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003649 std::string s = info.ToString(/*log_contents*/ true);
3650 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 }
3652 }
3653 }
3654 return NO_ERROR;
3655}
3656
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003657void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003658 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003659
3660 Mutex::Autolock l(mLogLock);
3661 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003662 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003663 }
3664
3665 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003666 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003667 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003668 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003669 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003670 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003671}
3672
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003673void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003674 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003675 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3676 if (mTorchClientMap[i] == who) {
3677 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003678 String8 cameraId = mTorchClientMap.keyAt(i);
3679 status_t res = mFlashlight->setTorchMode(cameraId, false);
3680 if (res) {
3681 ALOGE("%s: torch client died but couldn't turn off torch: "
3682 "%s (%d)", __FUNCTION__, strerror(-res), res);
3683 return;
3684 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003685 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003686 break;
3687 }
3688 }
3689}
3690
Ruben Brunkcc776712015-02-17 20:18:47 -08003691/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003692
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003693 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003694 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3695 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003696 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003697 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003698 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003699
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003700 // check torch client
3701 handleTorchClientBinderDied(who);
3702
3703 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003704 if(!evictClientIdByRemote(who)) {
3705 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003706 return;
3707 }
3708
Ruben Brunkcc776712015-02-17 20:18:47 -08003709 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3710 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003711}
3712
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003713void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003714 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003715}
3716
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003717void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3718 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 // Do not lock mServiceLock here or can get into a deadlock from
3720 // connect() -> disconnect -> updateStatus
3721
3722 auto state = getCameraState(cameraId);
3723
3724 if (state == nullptr) {
3725 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3726 cameraId.string());
3727 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003728 }
3729
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003730 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3731 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3732 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3733 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3734 return;
3735 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003736 bool supportsHAL3 = false;
3737 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3738 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3739 // mInterfaceMutex together, which can lead to deadlocks)
3740 binder::Status sRet =
3741 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3742 &supportsHAL3);
3743 if (!sRet.isOk()) {
3744 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3745 __FUNCTION__, cameraId.string());
3746 return;
3747 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003748 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003749 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003750 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003751 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003752
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003753 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003754 // Update torch status if it has a flash unit.
3755 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003756 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003757 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3758 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003759 TorchModeStatus newTorchStatus =
3760 status == StatusInternal::PRESENT ?
3761 TorchModeStatus::AVAILABLE_OFF :
3762 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003763 if (torchStatus != newTorchStatus) {
3764 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3765 }
3766 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003767 }
3768
3769 Mutex::Autolock lock(mStatusListenerLock);
3770
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003771 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003772
Ruben Brunkcc776712015-02-17 20:18:47 -08003773 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003774 bool isVendorListener = listener->isVendorListener();
3775 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3776 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003777 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003778 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003779 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003780 continue;
3781 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003782 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003783 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 }
3785 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003786}
3787
Shuzhen Wang695044d2020-03-06 09:02:23 -08003788void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3789 const String16& clientPackageName) {
3790 Mutex::Autolock lock(mStatusListenerLock);
3791
3792 for (const auto& it : mListenerList) {
3793 if (!it->isOpenCloseCallbackAllowed()) {
3794 continue;
3795 }
3796
3797 binder::Status ret;
3798 String16 cameraId64(cameraId);
3799 if (open) {
3800 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3801 } else {
3802 ret = it->getListener()->onCameraClosed(cameraId64);
3803 }
3804 if (!ret.isOk()) {
3805 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3806 ret.exceptionCode());
3807 }
3808 }
3809}
3810
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003811template<class Func>
3812void CameraService::CameraState::updateStatus(StatusInternal status,
3813 const String8& cameraId,
3814 std::initializer_list<StatusInternal> rejectSourceStates,
3815 Func onStatusUpdatedLocked) {
3816 Mutex::Autolock lock(mStatusLock);
3817 StatusInternal oldStatus = mStatus;
3818 mStatus = status;
3819
3820 if (oldStatus == status) {
3821 return;
3822 }
3823
3824 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3825 cameraId.string(), oldStatus, status);
3826
3827 if (oldStatus == StatusInternal::NOT_PRESENT &&
3828 (status != StatusInternal::PRESENT &&
3829 status != StatusInternal::ENUMERATING)) {
3830
3831 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3832 __FUNCTION__);
3833 mStatus = oldStatus;
3834 return;
3835 }
3836
3837 /**
3838 * Sometimes we want to conditionally do a transition.
3839 * For example if a client disconnects, we want to go to PRESENT
3840 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3841 */
3842 for (auto& rejectStatus : rejectSourceStates) {
3843 if (oldStatus == rejectStatus) {
3844 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3845 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3846 mStatus = oldStatus;
3847 return;
3848 }
3849 }
3850
3851 onStatusUpdatedLocked(cameraId, status);
3852}
3853
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003854void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003855 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003856 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3857 if (proxyBinder == nullptr) return;
3858 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003859 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003860}
3861
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003862status_t CameraService::getTorchStatusLocked(
3863 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003864 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003865 if (!status) {
3866 return BAD_VALUE;
3867 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003868 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3869 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003870 // invalid camera ID or the camera doesn't have a flash unit
3871 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003872 }
3873
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003874 *status = mTorchStatusMap.valueAt(index);
3875 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003876}
3877
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003878status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003879 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003880 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3881 if (index == NAME_NOT_FOUND) {
3882 return BAD_VALUE;
3883 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003884 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003885
3886 return OK;
3887}
3888
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003889void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId,
3890 SystemCameraKind deviceKind) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003891 Mutex::Autolock lock(mCameraStatesLock);
3892 for (const auto& state : mCameraStates) {
3893 std::vector<std::string> physicalCameraIds;
3894 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3895 // This is not a logical multi-camera.
3896 continue;
3897 }
3898 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3899 == physicalCameraIds.end()) {
3900 // cameraId is not a physical camera of this logical multi-camera.
3901 continue;
3902 }
3903
3904 String16 id16(state.first), physicalId16(cameraId);
3905 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003906 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3907 listener->getListenerPid(), listener->getListenerUid())) {
3908 ALOGV("Skipping discovery callback for system-only camera device %s",
3909 cameraId.c_str());
3910 continue;
3911 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003912 listener->getListener()->onPhysicalCameraStatusChanged(status,
3913 id16, physicalId16);
3914 }
3915 }
3916}
3917
Svet Ganova453d0d2018-01-11 15:37:58 -08003918void CameraService::blockClientsForUid(uid_t uid) {
3919 const auto clients = mActiveClientManager.getAll();
3920 for (auto& current : clients) {
3921 if (current != nullptr) {
3922 const auto basicClient = current->getValue();
3923 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3924 basicClient->block();
3925 }
3926 }
3927 }
3928}
3929
Michael Grooverd1d435a2018-12-18 17:39:42 -08003930void CameraService::blockAllClients() {
3931 const auto clients = mActiveClientManager.getAll();
3932 for (auto& current : clients) {
3933 if (current != nullptr) {
3934 const auto basicClient = current->getValue();
3935 if (basicClient.get() != nullptr) {
3936 basicClient->block();
3937 }
3938 }
3939 }
3940}
3941
Svet Ganova453d0d2018-01-11 15:37:58 -08003942// NOTE: This is a remote API - make sure all args are validated
3943status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3944 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3945 return PERMISSION_DENIED;
3946 }
3947 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3948 return BAD_VALUE;
3949 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003950 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003951 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003952 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003953 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003954 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003955 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003956 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3957 return handleSetRotateAndCrop(args);
3958 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3959 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003960 } else if (args.size() == 1 && args[0] == String16("help")) {
3961 printHelp(out);
3962 return NO_ERROR;
3963 }
3964 printHelp(err);
3965 return BAD_VALUE;
3966}
3967
3968status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003969 String16 packageName = args[1];
3970
Svet Ganova453d0d2018-01-11 15:37:58 -08003971 bool active = false;
3972 if (args[2] == String16("active")) {
3973 active = true;
3974 } else if ((args[2] != String16("idle"))) {
3975 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3976 return BAD_VALUE;
3977 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003978
3979 int userId = 0;
3980 if (args.size() >= 5 && args[3] == String16("--user")) {
3981 userId = atoi(String8(args[4]));
3982 }
3983
3984 uid_t uid;
3985 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3986 return BAD_VALUE;
3987 }
3988
3989 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003990 return NO_ERROR;
3991}
3992
3993status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003994 String16 packageName = args[1];
3995
3996 int userId = 0;
3997 if (args.size() >= 4 && args[2] == String16("--user")) {
3998 userId = atoi(String8(args[3]));
3999 }
4000
4001 uid_t uid;
4002 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004003 return BAD_VALUE;
4004 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004005
4006 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004007 return NO_ERROR;
4008}
4009
4010status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004011 String16 packageName = args[1];
4012
4013 int userId = 0;
4014 if (args.size() >= 4 && args[2] == String16("--user")) {
4015 userId = atoi(String8(args[3]));
4016 }
4017
4018 uid_t uid;
4019 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004020 return BAD_VALUE;
4021 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004022
4023 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004024 return dprintf(out, "active\n");
4025 } else {
4026 return dprintf(out, "idle\n");
4027 }
4028}
4029
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004030status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4031 int rotateValue = atoi(String8(args[1]));
4032 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4033 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4034 Mutex::Autolock lock(mServiceLock);
4035
4036 mOverrideRotateAndCropMode = rotateValue;
4037
4038 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4039
4040 const auto clients = mActiveClientManager.getAll();
4041 for (auto& current : clients) {
4042 if (current != nullptr) {
4043 const auto basicClient = current->getValue();
4044 if (basicClient.get() != nullptr) {
4045 basicClient->setRotateAndCropOverride(rotateValue);
4046 }
4047 }
4048 }
4049
4050 return OK;
4051}
4052
4053status_t CameraService::handleGetRotateAndCrop(int out) {
4054 Mutex::Autolock lock(mServiceLock);
4055
4056 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4057}
4058
Svet Ganova453d0d2018-01-11 15:37:58 -08004059status_t CameraService::printHelp(int out) {
4060 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004061 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4062 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4063 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004064 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4065 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4066 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004067 " help print this message\n");
4068}
4069
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004070int32_t CameraService::updateAudioRestriction() {
4071 Mutex::Autolock lock(mServiceLock);
4072 return updateAudioRestrictionLocked();
4073}
4074
4075int32_t CameraService::updateAudioRestrictionLocked() {
4076 int32_t mode = 0;
4077 // iterate through all active client
4078 for (const auto& i : mActiveClientManager.getAll()) {
4079 const auto clientSp = i->getValue();
4080 mode |= clientSp->getAudioRestriction();
4081 }
4082
4083 bool modeChanged = (mAudioRestriction != mode);
4084 mAudioRestriction = mode;
4085 if (modeChanged) {
4086 mAppOps.setCameraAudioRestriction(mode);
4087 }
4088 return mode;
4089}
4090
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091}; // namespace android