blob: ce2bec0098187bb12fe87740419fd8db3d4f5e8d [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
Jayant Chowdhary407571f2021-10-05 14:36:13 -0700509
510void CameraService::onTorchStatusChanged(const String8& cameraId,
511 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
512 Mutex::Autolock al(mTorchStatusMutex);
513 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
514}
515
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800516void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800518 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
519 __FUNCTION__, cameraId.string(), newStatus);
520
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800521 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800522 status_t res = getTorchStatusLocked(cameraId, &status);
523 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700524 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
525 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800526 return;
527 }
528 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800529 return;
530 }
531
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800532 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800533 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800534 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
535 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800536 return;
537 }
538
Ruben Brunkcc776712015-02-17 20:18:47 -0800539 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700540 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700541 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700542 auto iter = mTorchUidMap.find(cameraId);
543 if (iter != mTorchUidMap.end()) {
544 int oldUid = iter->second.second;
545 int newUid = iter->second.first;
546 BatteryNotifier& notifier(BatteryNotifier::getInstance());
547 if (oldUid != newUid) {
548 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800549 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700550 notifier.noteFlashlightOff(cameraId, oldUid);
551 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800552 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700553 notifier.noteFlashlightOn(cameraId, newUid);
554 }
555 iter->second.second = newUid;
556 } else {
557 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700559 notifier.noteFlashlightOn(cameraId, oldUid);
560 } else {
561 notifier.noteFlashlightOff(cameraId, oldUid);
562 }
563 }
564 }
565 }
566
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800567 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800568}
569
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700570static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
571 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
572 checkPermission(sCameraPermission, callingPid, callingUid);
573}
574
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800575Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700576 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100577 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700578 bool hasSystemCameraPermissions =
579 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
580 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700581 switch (type) {
582 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700583 if (hasSystemCameraPermissions) {
584 *numCameras = static_cast<int>(mNormalDeviceIds.size());
585 } else {
586 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
587 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700589 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700590 if (hasSystemCameraPermissions) {
591 *numCameras = mNumberOfCameras;
592 } else {
593 *numCameras = mNumberOfCamerasWithoutSystemCamera;
594 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800595 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700596 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800597 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700598 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800599 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
600 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700601 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800602 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603}
604
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800605Status CameraService::getCameraInfo(int cameraId,
606 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700607 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100608 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700609 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
610 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
611 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
612 "characteristics for system only device %s: ", cameraIdStr.c_str());
613 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100614
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800615 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800616 return STATUS_ERROR(ERROR_DISCONNECTED,
617 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700618 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700619 bool hasSystemCameraPermissions =
620 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
621 CameraThreadState::getCallingUid());
622 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
623 if (hasSystemCameraPermissions) {
624 cameraIdBound = mNumberOfCameras;
625 }
626 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800627 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
628 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 }
630
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800631 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800632 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700633 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100634 if (err != OK) {
635 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
636 "Error retrieving camera info from device %d: %s (%d)", cameraId,
637 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800638 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100639
Ruben Brunkcc776712015-02-17 20:18:47 -0800640 return ret;
641}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700642
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800643std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700644 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
645 auto callingPid = CameraThreadState::getCallingPid();
646 auto callingUid = CameraThreadState::getCallingUid();
647 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
648 getpid() == callingPid) {
649 deviceIds = &mNormalDeviceIds;
650 }
651 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800652 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700653 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800654 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800655 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800656
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700657 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800658}
659
660String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
661 Mutex::Autolock lock(mServiceLock);
662 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800663}
664
665Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800666 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700667 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700668 if (!cameraInfo) {
669 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800670 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700671 }
672
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800673 if (!mInitialized) {
674 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800675 return STATUS_ERROR(ERROR_DISCONNECTED,
676 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700677 }
678
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700679 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
680 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
681 "characteristics for system only device %s: ", String8(cameraId).string());
682 }
683
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800684 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800685
Emilian Peevf53f66e2017-04-11 14:29:43 +0100686 status_t res = mCameraProviderManager->getCameraCharacteristics(
687 String8(cameraId).string(), cameraInfo);
688 if (res != OK) {
689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
690 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
691 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700692 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700693 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
694 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
695 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
696 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
697 "for device %s", String8(cameraId).string());
698 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700699 int callingPid = CameraThreadState::getCallingPid();
700 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100701 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700702 // If it's not calling from cameraserver, check the permission only if
703 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
704 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100705 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700706 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700707 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100708 res = cameraInfo->removePermissionEntries(
709 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
710 &tagsRemoved);
711 if (res != OK) {
712 cameraInfo->clear();
713 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
714 " characteristics needing camera permission for device %s: %s (%d)",
715 String8(cameraId).string(), strerror(-res), res);
716 }
717 }
718
719 if (!tagsRemoved.empty()) {
720 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
721 tagsRemoved.data(), tagsRemoved.size());
722 if (res != OK) {
723 cameraInfo->clear();
724 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
725 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
726 strerror(-res), res);
727 }
728 }
729
Zhijun He2b59be82013-09-25 10:14:30 -0700730 return ret;
731}
732
Ruben Brunkcc776712015-02-17 20:18:47 -0800733String8 CameraService::getFormattedCurrentTime() {
734 time_t now = time(nullptr);
735 char formattedTime[64];
736 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
737 return String8(formattedTime);
738}
739
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800740Status CameraService::getCameraVendorTagDescriptor(
741 /*out*/
742 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700743 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800744 if (!mInitialized) {
745 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800746 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800747 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800748 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
749 if (globalDescriptor != nullptr) {
750 *desc = *(globalDescriptor.get());
751 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800752 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800753}
754
Emilian Peev71c73a22017-03-21 16:35:51 +0000755Status CameraService::getCameraVendorTagCache(
756 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
757 ATRACE_CALL();
758 if (!mInitialized) {
759 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
760 return STATUS_ERROR(ERROR_DISCONNECTED,
761 "Camera subsystem not available");
762 }
763 sp<VendorTagDescriptorCache> globalCache =
764 VendorTagDescriptorCache::getGlobalVendorTagCache();
765 if (globalCache != nullptr) {
766 *cache = *(globalCache.get());
767 }
768 return Status::ok();
769}
770
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800771int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700772 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800773
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800774 int deviceVersion = 0;
775
Emilian Peevf53f66e2017-04-11 14:29:43 +0100776 status_t res;
777 hardware::hidl_version maxVersion{0,0};
778 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
779 &maxVersion);
780 if (res != OK) return -1;
781 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800782
Emilian Peevf53f66e2017-04-11 14:29:43 +0100783 hardware::CameraInfo info;
784 if (facing) {
785 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800786 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100787 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800788 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100789
Igor Murashkin634a5152013-02-20 17:15:11 -0800790 return deviceVersion;
791}
792
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800793Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700794 switch(err) {
795 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800796 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800797 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800798 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
799 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800800 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800801 return STATUS_ERROR(ERROR_DISCONNECTED,
802 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700803 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800804 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
805 "Camera HAL encountered error %d: %s",
806 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700807 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800808}
809
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800810Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800811 const sp<IInterface>& cameraCb, const String16& packageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900812 const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800813 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
814 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800815 /*out*/sp<BasicClient>* client) {
816
Ruben Brunkcc776712015-02-17 20:18:47 -0800817 if (halVersion < 0 || halVersion == deviceVersion) {
818 // Default path: HAL version is unspecified by caller, create CameraClient
819 // based on device version reported by the HAL.
820 switch(deviceVersion) {
821 case CAMERA_DEVICE_API_VERSION_1_0:
822 if (effectiveApiLevel == API_1) { // Camera1 API route
823 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800824 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800825 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700826 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800827 } else { // Camera2 API route
828 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800830 "Camera device \"%s\" HAL version %d does not support camera2 API",
831 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800832 }
833 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800834 case CAMERA_DEVICE_API_VERSION_3_0:
835 case CAMERA_DEVICE_API_VERSION_3_1:
836 case CAMERA_DEVICE_API_VERSION_3_2:
837 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700838 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700839 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800840 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800841 if (effectiveApiLevel == API_1) { // Camera1 API route
842 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800843 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800844 cameraId, api1CameraId,
845 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700846 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800847 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800848 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
849 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800850 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
851 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800852 }
853 break;
854 default:
855 // Should not be reachable
856 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800857 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800858 "Camera device \"%s\" has unknown HAL version %d",
859 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800860 }
861 } else {
862 // A particular HAL version is requested by caller. Create CameraClient
863 // based on the requested HAL version.
864 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
865 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
866 // Only support higher HAL version device opened as HAL1.0 device.
867 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800868 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800869 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700870 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800871 } else {
872 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
873 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
874 " opened as HAL %x device", halVersion, deviceVersion,
875 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800876 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800877 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
878 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800879 }
880 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800881 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800882}
883
Ruben Brunk6267b532015-04-30 17:44:07 -0700884String8 CameraService::toString(std::set<userid_t> intSet) {
885 String8 s("");
886 bool first = true;
887 for (userid_t i : intSet) {
888 if (first) {
889 s.appendFormat("%d", i);
890 first = false;
891 } else {
892 s.appendFormat(", %d", i);
893 }
894 }
895 return s;
896}
897
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800898int32_t CameraService::mapToInterface(TorchModeStatus status) {
899 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
900 switch (status) {
901 case TorchModeStatus::NOT_AVAILABLE:
902 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
903 break;
904 case TorchModeStatus::AVAILABLE_OFF:
905 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
906 break;
907 case TorchModeStatus::AVAILABLE_ON:
908 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
909 break;
910 default:
911 ALOGW("Unknown new flash status: %d", status);
912 }
913 return serviceStatus;
914}
915
916CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
917 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
918 switch (status) {
919 case CameraDeviceStatus::NOT_PRESENT:
920 serviceStatus = StatusInternal::NOT_PRESENT;
921 break;
922 case CameraDeviceStatus::PRESENT:
923 serviceStatus = StatusInternal::PRESENT;
924 break;
925 case CameraDeviceStatus::ENUMERATING:
926 serviceStatus = StatusInternal::ENUMERATING;
927 break;
928 default:
929 ALOGW("Unknown new HAL device status: %d", status);
930 }
931 return serviceStatus;
932}
933
934int32_t CameraService::mapToInterface(StatusInternal status) {
935 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
936 switch (status) {
937 case StatusInternal::NOT_PRESENT:
938 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
939 break;
940 case StatusInternal::PRESENT:
941 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
942 break;
943 case StatusInternal::ENUMERATING:
944 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
945 break;
946 case StatusInternal::NOT_AVAILABLE:
947 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
948 break;
949 case StatusInternal::UNKNOWN:
950 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
951 break;
952 default:
953 ALOGW("Unknown new internal device status: %d", status);
954 }
955 return serviceStatus;
956}
957
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800958Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700959 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700960
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800961 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800962 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800963 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800964 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800966 sp<ICameraClient>{nullptr}, id, cameraId,
967 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900968 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700969 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800970 ).isOk()) {
971 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700972 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800973 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700974}
975
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800976Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700977 /*out*/
978 CameraParameters* parameters) {
979
980 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
981
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800982 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700983
984 if (parameters == NULL) {
985 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800986 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700987 }
988
Ruben Brunkcc776712015-02-17 20:18:47 -0800989 String8 id = String8::format("%d", cameraId);
990
991 // Check if we already have parameters
992 {
993 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700994 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800995 auto cameraState = getCameraState(id);
996 if (cameraState == nullptr) {
997 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800998 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
999 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001000 }
1001 CameraParameters p = cameraState->getShimParams();
1002 if (!p.isEmpty()) {
1003 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001004 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001005 }
1006 }
1007
Jayant Chowdhary12361932018-08-27 14:46:13 -07001008 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001009 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001010 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001011 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001012 // Error already logged by callee
1013 return ret;
1014 }
1015
1016 // Check for parameters again
1017 {
1018 // Scope for service lock
1019 Mutex::Autolock lock(mServiceLock);
1020 auto cameraState = getCameraState(id);
1021 if (cameraState == nullptr) {
1022 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001023 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1024 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001025 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001026 CameraParameters p = cameraState->getShimParams();
1027 if (!p.isEmpty()) {
1028 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001029 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001030 }
1031 }
1032
Ruben Brunkcc776712015-02-17 20:18:47 -08001033 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1034 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001035 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001036}
1037
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001038// Can camera service trust the caller based on the calling UID?
1039static bool isTrustedCallingUid(uid_t uid) {
1040 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001041 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001042 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001043 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001044 return true;
1045 default:
1046 return false;
1047 }
1048}
1049
Nicholas Sauera3620332019-04-03 14:05:17 -07001050static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1051 PermissionController pc;
1052 uid = pc.getPackageUid(packageName, 0);
1053 if (uid <= 0) {
1054 ALOGE("Unknown package: '%s'", String8(packageName).string());
1055 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1056 return BAD_VALUE;
1057 }
1058
1059 if (userId < 0) {
1060 ALOGE("Invalid user: %d", userId);
1061 dprintf(err, "Invalid user: %d\n", userId);
1062 return BAD_VALUE;
1063 }
1064
1065 uid = multiuser_get_uid(userId, uid);
1066 return NO_ERROR;
1067}
1068
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001069Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001070 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1071 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001072
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001073#ifdef __BRILLO__
1074 UNUSED(clientName8);
1075 UNUSED(clientUid);
1076 UNUSED(clientPid);
1077 UNUSED(originalClientPid);
1078#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001079 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1080 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001081 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001082 return allowed;
1083 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001084#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001085
Jayant Chowdhary12361932018-08-27 14:46:13 -07001086 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001087
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001088 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001089 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1090 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001091 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1092 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001093 }
1094
Ruben Brunkcc776712015-02-17 20:18:47 -08001095 if (getCameraState(cameraId) == nullptr) {
1096 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1097 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001098 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1099 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 }
1101
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001102 status_t err = checkIfDeviceIsUsable(cameraId);
1103 if (err != NO_ERROR) {
1104 switch(err) {
1105 case -ENODEV:
1106 case -EBUSY:
1107 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1108 "No camera device with ID \"%s\" currently available", cameraId.string());
1109 default:
1110 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1111 "Unknown error connecting to ID \"%s\"", cameraId.string());
1112 }
1113 }
1114 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001115}
1116
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001117Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001118 const String8& clientName8, int& clientUid, int& clientPid,
1119 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001120 int callingPid = CameraThreadState::getCallingPid();
1121 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001123 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001125 clientUid = callingUid;
1126 } else if (!isTrustedCallingUid(callingUid)) {
1127 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1128 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001129 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1130 "Untrusted caller (calling PID %d, UID %d) trying to "
1131 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1132 callingPid, callingUid, cameraId.string(),
1133 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134 }
1135
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001136 // Check if we can trust clientPid
1137 if (clientPid == USE_CALLING_PID) {
1138 clientPid = callingPid;
1139 } else if (!isTrustedCallingUid(callingUid)) {
1140 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1141 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001142 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1143 "Untrusted caller (calling PID %d, UID %d) trying to "
1144 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1145 callingPid, callingUid, cameraId.string(),
1146 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001147 }
1148
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001149 if (shouldRejectSystemCameraConnection(cameraId)) {
1150 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1151 cameraId.c_str());
1152 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1153 "available", cameraId.string());
1154 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001155 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1156 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1157 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1158 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1159 "found while trying to query device kind", cameraId.string());
1160
1161 }
1162
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001163 // If it's not calling from cameraserver, check the permission if the
1164 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1165 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001166 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001167 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001168 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001169 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001170 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1171 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1172 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001173 }
1174
Svet Ganova453d0d2018-01-11 15:37:58 -08001175 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001176 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001177 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001178 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1179 clientPid, clientUid);
1180 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001181 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1182 "calling UID %d proc state %" PRId32 ")",
1183 clientName8.string(), clientUid, clientPid, cameraId.string(),
1184 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001185 }
1186
Michael Grooverd1d435a2018-12-18 17:39:42 -08001187 // If sensor privacy is enabled then prevent access to the camera
1188 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1189 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1190 return STATUS_ERROR_FMT(ERROR_DISABLED,
1191 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1192 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1193 }
1194
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001195 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1196 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001197 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001198 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199
Ruben Brunk6267b532015-04-30 17:44:07 -07001200 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001201
Ruben Brunka8ca9152015-04-07 14:23:40 -07001202 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001203 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001204 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001205 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001206 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1207 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1208 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001209 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1210 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1211 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001212 }
1213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001214 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001215}
1216
1217status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1218 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001219 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001220 if (cameraState == nullptr) {
1221 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1222 cameraId.string());
1223 return -ENODEV;
1224 }
1225
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001226 StatusInternal currentStatus = cameraState->getStatus();
1227 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001228 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1229 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001230 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001231 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001232 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1233 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001234 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001235 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001236
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001238}
1239
Ruben Brunkcc776712015-02-17 20:18:47 -08001240void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1241 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001242
Ruben Brunkcc776712015-02-17 20:18:47 -08001243 // Make a descriptor for the incoming client
1244 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1245 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1246
1247 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1248 String8(client->getPackageName()));
1249
1250 if (evicted.size() > 0) {
1251 // This should never happen - clients should already have been removed in disconnect
1252 for (auto& i : evicted) {
1253 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1254 __FUNCTION__, i->getKey().string());
1255 }
1256
1257 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1258 __FUNCTION__);
1259 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001260
1261 // And register a death notification for the client callback. Do
1262 // this last to avoid Binder policy where a nested Binder
1263 // transaction might be pre-empted to service the client death
1264 // notification if the client process dies before linkToDeath is
1265 // invoked.
1266 sp<IBinder> remoteCallback = client->getRemote();
1267 if (remoteCallback != nullptr) {
1268 remoteCallback->linkToDeath(this);
1269 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001270}
1271
1272status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1273 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1274 /*out*/
1275 sp<BasicClient>* client,
1276 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001277 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001279 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001280 DescriptorPtr clientDescriptor;
1281 {
1282 if (effectiveApiLevel == API_1) {
1283 // If we are using API1, any existing client for this camera ID with the same remote
1284 // should be returned rather than evicted to allow MediaRecorder to work properly.
1285
1286 auto current = mActiveClientManager.get(cameraId);
1287 if (current != nullptr) {
1288 auto clientSp = current->getValue();
1289 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001290 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1291 ALOGW("CameraService connect called from same client, but with a different"
1292 " API level, evicting prior client...");
1293 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001294 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001295 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001296 *client = clientSp;
1297 return NO_ERROR;
1298 }
1299 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001300 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001301 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001302
Ruben Brunkcc776712015-02-17 20:18:47 -08001303 // Get current active client PIDs
1304 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1305 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001306
Emilian Peev8131a262017-02-01 12:33:43 +00001307 std::vector<int> priorityScores(ownerPids.size());
1308 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001309
Emilian Peev8131a262017-02-01 12:33:43 +00001310 // Get priority scores of all active PIDs
1311 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1312 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1313 /*out*/&priorityScores[0]);
1314 if (err != OK) {
1315 ALOGE("%s: Priority score query failed: %d",
1316 __FUNCTION__, err);
1317 return err;
1318 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001319
Ruben Brunkcc776712015-02-17 20:18:47 -08001320 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001321 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001323 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001324 resource_policy::ClientPriority(priorityScores[i], states[i],
1325 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001326 }
1327 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001328
Ruben Brunkcc776712015-02-17 20:18:47 -08001329 // Get state for the given cameraId
1330 auto state = getCameraState(cameraId);
1331 if (state == nullptr) {
1332 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1333 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001334 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001335 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001336 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001337
1338 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001339 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001340 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1341 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001342 priorityScores[priorityScores.size() - 1],
1343 clientPid,
1344 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001345
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001346 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1347
Ruben Brunkcc776712015-02-17 20:18:47 -08001348 // Find clients that would be evicted
1349 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1350
1351 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1352 // background, so we cannot do evictions
1353 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1354 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1355 " priority).", clientPid);
1356
1357 sp<BasicClient> clientSp = clientDescriptor->getValue();
1358 String8 curTime = getFormattedCurrentTime();
1359 auto incompatibleClients =
1360 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1361
1362 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001363 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001364 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001365 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001366
1367 for (auto& i : incompatibleClients) {
1368 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001369 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1370 i->getKey().string(),
1371 String8{i->getValue()->getPackageName()}.string(),
1372 i->getOwnerId(), i->getPriority().getScore(),
1373 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001374 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001375 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001376 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001377 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 }
1379
1380 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001381 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 mEventLog.add(msg);
1383
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001384 auto current = mActiveClientManager.get(cameraId);
1385 if (current != nullptr) {
1386 return -EBUSY; // CAMERA_IN_USE
1387 } else {
1388 return -EUSERS; // MAX_CAMERAS_IN_USE
1389 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001390 }
1391
1392 for (auto& i : evicted) {
1393 sp<BasicClient> clientSp = i->getValue();
1394 if (clientSp.get() == nullptr) {
1395 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1396
1397 // TODO: Remove this
1398 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1399 __FUNCTION__);
1400 mActiveClientManager.remove(i);
1401 continue;
1402 }
1403
1404 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1405 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001406 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001407
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001409 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001410 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1411 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001412 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001413 i->getOwnerId(), i->getPriority().getScore(),
1414 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001415 packageName.string(), clientPid, clientPriority.getScore(),
1416 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001417
1418 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001419 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001421 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001422 }
1423
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1425 // other clients from connecting in mServiceLockWrapper if held
1426 mServiceLock.unlock();
1427
1428 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001429 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001430
1431 // Destroy evicted clients
1432 for (auto& i : evictedClients) {
1433 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001434 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001436
Jayant Chowdhary12361932018-08-27 14:46:13 -07001437 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001438
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001439 for (const auto& i : evictedClients) {
1440 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1441 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1442 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1443 if (ret == TIMED_OUT) {
1444 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1445 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1446 mActiveClientManager.toString().string());
1447 return -EBUSY;
1448 }
1449 if (ret != NO_ERROR) {
1450 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1451 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1452 ret, mActiveClientManager.toString().string());
1453 return ret;
1454 }
1455 }
1456
1457 evictedClients.clear();
1458
Ruben Brunkcc776712015-02-17 20:18:47 -08001459 // Once clients have been disconnected, relock
1460 mServiceLock.lock();
1461
1462 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1463 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1464 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001465 }
1466
Ruben Brunkcc776712015-02-17 20:18:47 -08001467 *partial = clientDescriptor;
1468 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001469}
1470
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001472 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001473 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001474 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001475 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001476 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001477 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001478 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001479
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001480 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001481 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001482
1483 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001484 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001485 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001486 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, {},
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001487 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001488
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001489 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001490 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001491 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001492 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 }
1494
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001495 *device = client;
1496 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497}
1498
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001499Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001500 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001501 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001502 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001503 int clientUid,
1504 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001505 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001506
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001507 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001508 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001509
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001510 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001511 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001512 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001513 clientPackageName, {}, clientUid, USE_CALLING_PID, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001514 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001515
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001516 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001517 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001518 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001519 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001520 }
1521
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 *device = client;
1523 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001524}
1525
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001526bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1527 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001528 // If the client is not a vendor client, don't add listener if
1529 // a) the camera is a publicly hidden secure camera OR
1530 // b) the camera is a system only camera and the client doesn't
1531 // have android.permission.SYSTEM_CAMERA permissions.
1532 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1533 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1534 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001535 return true;
1536 }
1537 return false;
1538}
1539
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001540bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1541 // Rules for rejection:
1542 // 1) If cameraserver tries to access this camera device, accept the
1543 // connection.
1544 // 2) The camera device is a publicly hidden secure camera device AND some
1545 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1546 // reject it.
1547 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1548 // and the serving thread is a non hwbinder thread, the client must have
1549 // android.permission.SYSTEM_CAMERA permissions to connect.
1550
1551 int cPid = CameraThreadState::getCallingPid();
1552 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001553 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1554 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1555 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1556 return true;
1557 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001558
1559 // (1) Cameraserver trying to connect, accept.
1560 if (CameraThreadState::getCallingPid() == getpid()) {
1561 return false;
1562 }
1563 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001564 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001565 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1566 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1567 return true;
1568 }
1569 // (3) Here we only check for permissions if it is a system only camera device. This is since
1570 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1571 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1572 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001573 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001574 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1575 !hasPermissionsForSystemCamera(cPid, cUid)) {
1576 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1577 cameraId.c_str());
1578 return true;
1579 }
1580
1581 return false;
1582}
1583
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584Status CameraService::connectDevice(
1585 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001586 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001587 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001588 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 int clientUid,
1590 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001591 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001592
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001593 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001595 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001596 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001597 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001598
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001599 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001600 std::string vendorClient =
1601 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1602 clientPackageNameAdj = String16(vendorClient.c_str());
1603 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001604 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001605 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001606 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001607 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001608
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001610 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001611 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001612 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001613 }
1614
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001615 *device = client;
1616 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001617}
1618
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001619template<class CALLBACK, class CLIENT>
1620Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001621 int api1CameraId, int halVersion, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001622 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001623 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001624 /*out*/sp<CLIENT>& device) {
1625 binder::Status ret = binder::Status::ok();
1626
1627 String8 clientName8(clientPackageName);
1628
1629 int originalClientPid = 0;
1630
1631 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1632 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1633 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1634 static_cast<int>(effectiveApiLevel));
1635
1636 sp<CLIENT> client = nullptr;
1637 {
1638 // Acquire mServiceLock and prevent other clients from connecting
1639 std::unique_ptr<AutoConditionLock> lock =
1640 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1641
1642 if (lock == nullptr) {
1643 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1644 , clientPid);
1645 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1646 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1647 cameraId.string(), clientName8.string(), clientPid);
1648 }
1649
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001650 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001651 if(!(ret = validateConnectLocked(cameraId, clientName8,
1652 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1653 return ret;
1654 }
1655
1656 // Check the shim parameters after acquiring lock, if they have already been updated and
1657 // we were doing a shim update, return immediately
1658 if (shimUpdateOnly) {
1659 auto cameraState = getCameraState(cameraId);
1660 if (cameraState != nullptr) {
1661 if (!cameraState->getShimParams().isEmpty()) return ret;
1662 }
1663 }
1664
1665 status_t err;
1666
1667 sp<BasicClient> clientTmp = nullptr;
1668 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1669 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1670 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1671 /*out*/&partial)) != NO_ERROR) {
1672 switch (err) {
1673 case -ENODEV:
1674 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1675 "No camera device with ID \"%s\" currently available",
1676 cameraId.string());
1677 case -EBUSY:
1678 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1679 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1680 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001681 case -EUSERS:
1682 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1683 "Too many cameras already open, cannot open camera \"%s\"",
1684 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001685 default:
1686 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1687 "Unexpected error %s (%d) opening camera \"%s\"",
1688 strerror(-err), err, cameraId.string());
1689 }
1690 }
1691
1692 if (clientTmp.get() != nullptr) {
1693 // Handle special case for API1 MediaRecorder where the existing client is returned
1694 device = static_cast<CLIENT*>(clientTmp.get());
1695 return ret;
1696 }
1697
1698 // give flashlight a chance to close devices if necessary.
1699 mFlashlight->prepareDeviceOpen(cameraId);
1700
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001701 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001702 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001703 if (facing == -1) {
1704 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1705 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1706 "Unable to get camera device \"%s\" facing", cameraId.string());
1707 }
1708
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001709 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001710 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001711 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001712 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001713 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001714 /*out*/&tmp)).isOk()) {
1715 return ret;
1716 }
1717 client = static_cast<CLIENT*>(tmp.get());
1718
1719 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1720 __FUNCTION__);
1721
Emilian Peevbd8c5032018-02-14 23:05:40 +00001722 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001723 if (err != OK) {
1724 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001725 // Errors could be from the HAL module open call or from AppOpsManager
1726 switch(err) {
1727 case BAD_VALUE:
1728 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1729 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1730 case -EBUSY:
1731 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1732 "Camera \"%s\" is already open", cameraId.string());
1733 case -EUSERS:
1734 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1735 "Too many cameras already open, cannot open camera \"%s\"",
1736 cameraId.string());
1737 case PERMISSION_DENIED:
1738 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1739 "No permission to open camera \"%s\"", cameraId.string());
1740 case -EACCES:
1741 return STATUS_ERROR_FMT(ERROR_DISABLED,
1742 "Camera \"%s\" disabled by policy", cameraId.string());
1743 case -ENODEV:
1744 default:
1745 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1746 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1747 strerror(-err), err);
1748 }
1749 }
1750
1751 // Update shim paremeters for legacy clients
1752 if (effectiveApiLevel == API_1) {
1753 // Assume we have always received a Client subclass for API1
1754 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1755 String8 rawParams = shimClient->getParameters();
1756 CameraParameters params(rawParams);
1757
1758 auto cameraState = getCameraState(cameraId);
1759 if (cameraState != nullptr) {
1760 cameraState->setShimParams(params);
1761 } else {
1762 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1763 __FUNCTION__, cameraId.string());
1764 }
1765 }
1766
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001767 // Set rotate-and-crop override behavior
1768 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1769 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1770 }
1771
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001772 if (shimUpdateOnly) {
1773 // If only updating legacy shim parameters, immediately disconnect client
1774 mServiceLock.unlock();
1775 client->disconnect();
1776 mServiceLock.lock();
1777 } else {
1778 // Otherwise, add client to active clients list
1779 finishConnectLocked(client, partial);
1780 }
1781 } // lock is destroyed, allow further connect calls
1782
1783 // Important: release the mutex here so the client can call back into the service from its
1784 // destructor (can be at the end of the call)
1785 device = client;
1786 return ret;
1787}
1788
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001789status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1790 if (offlineClient.get() == nullptr) {
1791 return BAD_VALUE;
1792 }
1793
1794 {
1795 // Acquire mServiceLock and prevent other clients from connecting
1796 std::unique_ptr<AutoConditionLock> lock =
1797 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1798
1799 if (lock == nullptr) {
1800 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1801 , __FUNCTION__, offlineClient->getClientPid());
1802 return TIMED_OUT;
1803 }
1804
1805 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1806 if (onlineClientDesc.get() == nullptr) {
1807 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1808 cameraId.c_str());
1809 return BAD_VALUE;
1810 }
1811
1812 // Offline clients do not evict or conflict with other online devices. Resource sharing
1813 // conflicts are handled by the camera provider which will either succeed or fail before
1814 // reaching this method.
1815 const auto& onlinePriority = onlineClientDesc->getPriority();
1816 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1817 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1818 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1819 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1820
1821 // Allow only one offline device per camera
1822 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1823 if (!incompatibleClients.empty()) {
1824 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1825 return BAD_VALUE;
1826 }
1827
1828 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1829 if (err != OK) {
1830 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1831 return err;
1832 }
1833
1834 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1835 if (evicted.size() > 0) {
1836 for (auto& i : evicted) {
1837 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1838 __FUNCTION__, i->getKey().string());
1839 }
1840
1841 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1842 "properly", __FUNCTION__);
1843
1844 return BAD_VALUE;
1845 }
1846
1847 logConnectedOffline(offlineClientDesc->getKey(),
1848 static_cast<int>(offlineClientDesc->getOwnerId()),
1849 String8(offlineClient->getPackageName()));
1850
1851 sp<IBinder> remoteCallback = offlineClient->getRemote();
1852 if (remoteCallback != nullptr) {
1853 remoteCallback->linkToDeath(this);
1854 }
1855 } // lock is destroyed, allow further connect calls
1856
1857 return OK;
1858}
1859
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001861 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001862 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001863
1864 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001865 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001866 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001867 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1868 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001869 }
1870
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001871 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001872 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001873
1874 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001875 auto state = getCameraState(id);
1876 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001877 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001878 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1879 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001880 }
1881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001882 StatusInternal cameraStatus = state->getStatus();
1883 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001884 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1885 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001886 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1887 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001888 }
1889
1890 {
1891 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001892 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001893 status_t err = getTorchStatusLocked(id, &status);
1894 if (err != OK) {
1895 if (err == NAME_NOT_FOUND) {
1896 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1897 "Camera \"%s\" does not have a flash unit", id.string());
1898 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001899 ALOGE("%s: getting current torch status failed for camera %s",
1900 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001901 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1902 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1903 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001904 }
1905
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001906 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001907 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001908 ALOGE("%s: torch mode of camera %s is not available because "
1909 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001910 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1911 "Torch for camera \"%s\" is not available due to an existing camera user",
1912 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001913 } else {
1914 ALOGE("%s: torch mode of camera %s is not available due to "
1915 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001916 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1917 "Torch for camera \"%s\" is not available due to insufficient resources",
1918 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001919 }
1920 }
1921 }
1922
Ruben Brunk99e69712015-05-26 17:25:07 -07001923 {
1924 // Update UID map - this is used in the torch status changed callbacks, so must be done
1925 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001926 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001927 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1928 mTorchUidMap[id].first = uid;
1929 mTorchUidMap[id].second = uid;
1930 } else {
1931 // Set the pending UID
1932 mTorchUidMap[id].first = uid;
1933 }
1934 }
1935
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001936 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001937
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001938 if (err != OK) {
1939 int32_t errorCode;
1940 String8 msg;
1941 switch (err) {
1942 case -ENOSYS:
1943 msg = String8::format("Camera \"%s\" has no flashlight",
1944 id.string());
1945 errorCode = ERROR_ILLEGAL_ARGUMENT;
1946 break;
1947 default:
1948 msg = String8::format(
1949 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1950 id.string(), enabled, strerror(-err), err);
1951 errorCode = ERROR_INVALID_OPERATION;
1952 }
1953 ALOGE("%s: %s", __FUNCTION__, msg.string());
1954 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001955 }
1956
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001957 {
1958 // update the link to client's death
1959 Mutex::Autolock al(mTorchClientMapMutex);
1960 ssize_t index = mTorchClientMap.indexOfKey(id);
1961 if (enabled) {
1962 if (index == NAME_NOT_FOUND) {
1963 mTorchClientMap.add(id, clientBinder);
1964 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001965 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001966 mTorchClientMap.replaceValueAt(index, clientBinder);
1967 }
1968 clientBinder->linkToDeath(this);
1969 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001970 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001971 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001972 }
1973
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001974 int clientPid = CameraThreadState::getCallingPid();
1975 const char *id_cstr = id.c_str();
1976 const char *torchState = enabled ? "on" : "off";
1977 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1978 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001979 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001980}
1981
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001982Status CameraService::notifySystemEvent(int32_t eventId,
1983 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001984 const int pid = CameraThreadState::getCallingPid();
1985 const int selfPid = getpid();
1986
1987 // Permission checks
1988 if (pid != selfPid) {
1989 // Ensure we're being called by system_server, or similar process with
1990 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001991 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001992 const int uid = CameraThreadState::getCallingUid();
1993 ALOGE("Permission Denial: cannot send updates to camera service about system"
1994 " events from pid=%d, uid=%d", pid, uid);
1995 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001996 "No permission to send updates to camera service about system events"
1997 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001998 }
1999 }
2000
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002001 ATRACE_CALL();
2002
Ruben Brunk36597b22015-03-20 22:15:57 -07002003 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002004 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002005 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002006 // from a system server crash
2007 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002008 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002009 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002010 break;
2011 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002012 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002013 default: {
2014 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2015 eventId);
2016 break;
2017 }
2018 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002019 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002020}
2021
Emilian Peev53722fa2019-02-22 17:47:20 -08002022void CameraService::notifyMonitoredUids() {
2023 Mutex::Autolock lock(mStatusListenerLock);
2024
2025 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002026 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002027 if (!ret.isOk()) {
2028 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2029 ret.exceptionCode());
2030 }
2031 }
2032}
2033
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002034Status CameraService::notifyDeviceStateChange(int64_t newState) {
2035 const int pid = CameraThreadState::getCallingPid();
2036 const int selfPid = getpid();
2037
2038 // Permission checks
2039 if (pid != selfPid) {
2040 // Ensure we're being called by system_server, or similar process with
2041 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002042 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002043 const int uid = CameraThreadState::getCallingUid();
2044 ALOGE("Permission Denial: cannot send updates to camera service about device"
2045 " state changes from pid=%d, uid=%d", pid, uid);
2046 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2047 "No permission to send updates to camera service about device state"
2048 " changes from pid=%d, uid=%d", pid, uid);
2049 }
2050 }
2051
2052 ATRACE_CALL();
2053
2054 using hardware::camera::provider::V2_5::DeviceState;
2055 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2056 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2057 newDeviceState |= DeviceState::BACK_COVERED;
2058 }
2059 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2060 newDeviceState |= DeviceState::FRONT_COVERED;
2061 }
2062 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2063 newDeviceState |= DeviceState::FOLDED;
2064 }
2065 // Only map vendor bits directly
2066 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2067 newDeviceState |= vendorBits;
2068
2069 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2070 Mutex::Autolock l(mServiceLock);
2071 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2072
2073 return Status::ok();
2074}
2075
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002076 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002077 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2078 ATRACE_CALL();
2079 if (!concurrentCameraIds) {
2080 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2081 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2082 }
2083
2084 if (!mInitialized) {
2085 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2086 return STATUS_ERROR(ERROR_DISCONNECTED,
2087 "Camera subsystem is not available");
2088 }
2089 // First call into the provider and get the set of concurrent camera
2090 // combinations
2091 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002092 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002093 for (auto &combination : concurrentCameraCombinations) {
2094 std::vector<std::string> validCombination;
2095 for (auto &cameraId : combination) {
2096 // if the camera state is not present, skip
2097 String8 cameraIdStr(cameraId.c_str());
2098 auto state = getCameraState(cameraIdStr);
2099 if (state == nullptr) {
2100 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2101 continue;
2102 }
2103 StatusInternal status = state->getStatus();
2104 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2105 continue;
2106 }
2107 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2108 continue;
2109 }
2110 validCombination.push_back(cameraId);
2111 }
2112 if (validCombination.size() != 0) {
2113 concurrentCameraIds->push_back(std::move(validCombination));
2114 }
2115 }
2116 return Status::ok();
2117}
2118
2119Status CameraService::isConcurrentSessionConfigurationSupported(
2120 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2121 /*out*/bool* isSupported) {
2122 if (!isSupported) {
2123 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2124 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2125 }
2126
2127 if (!mInitialized) {
2128 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2129 return STATUS_ERROR(ERROR_DISCONNECTED,
2130 "Camera subsystem is not available");
2131 }
2132
2133 // Check for camera permissions
2134 int callingPid = CameraThreadState::getCallingPid();
2135 int callingUid = CameraThreadState::getCallingUid();
2136 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2137 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2138 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2139 "android.permission.CAMERA needed to call"
2140 "isConcurrentSessionConfigurationSupported");
2141 }
2142
2143 status_t res =
2144 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2145 cameraIdsAndSessionConfigurations, isSupported);
2146 if (res != OK) {
2147 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2148 "support %s (%d)", strerror(-res), res);
2149 }
2150 return Status::ok();
2151}
2152
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002153Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2154 /*out*/
2155 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002156 return addListenerHelper(listener, cameraStatuses);
2157}
2158
2159Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2160 /*out*/
2161 std::vector<hardware::CameraStatus> *cameraStatuses,
2162 bool isVendorListener) {
2163
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002164 ATRACE_CALL();
2165
Igor Murashkinbfc99152013-02-27 12:55:20 -08002166 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002167
Ruben Brunk3450ba72015-06-16 11:00:37 -07002168 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002169 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002170 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002171 }
2172
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002173 auto clientUid = CameraThreadState::getCallingUid();
2174 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002175 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2176 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002177
Igor Murashkinbfc99152013-02-27 12:55:20 -08002178 Mutex::Autolock lock(mServiceLock);
2179
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 {
2181 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002182 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002184 ALOGW("%s: Tried to add listener %p which was already subscribed",
2185 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002186 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002187 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002188 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002189
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002190 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002191 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2192 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002193 auto ret = serviceListener->initialize();
2194 if (ret != NO_ERROR) {
2195 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2196 strerror(-ret), ret);
2197 ALOGE("%s: %s", __FUNCTION__, msg.string());
2198 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2199 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200 // The listener still needs to be added to the list of listeners, regardless of what
2201 // permissions the listener process has / whether it is a vendor listener. Since it might be
2202 // eligible to listen to other camera ids.
2203 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002204 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002205 }
2206
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002207 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002208 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002209 Mutex::Autolock lock(mCameraStatesLock);
2210 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002211 cameraStatuses->emplace_back(i.first,
2212 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002213 }
2214 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002215 // Remove the camera statuses that should be hidden from the client, we do
2216 // this after collecting the states in order to avoid holding
2217 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2218 // the same time.
2219 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2220 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2221 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2222 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2223 ALOGE("%s: Invalid camera id %s, skipping status update",
2224 __FUNCTION__, s.cameraId.c_str());
2225 return true;
2226 }
2227 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2228 clientUid);}), cameraStatuses->end());
2229
Igor Murashkincba2c162013-03-20 15:56:31 -07002230
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002231 /*
2232 * Immediately signal current torch status to this listener only
2233 * This may be a subset of all the devices, so don't include it in the response directly
2234 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002235 {
2236 Mutex::Autolock al(mTorchStatusMutex);
2237 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002238 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002239 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002240 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002241 }
2242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002244}
Ruben Brunkcc776712015-02-17 20:18:47 -08002245
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002247 ATRACE_CALL();
2248
Igor Murashkinbfc99152013-02-27 12:55:20 -08002249 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2250
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002251 if (listener == 0) {
2252 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002254 }
2255
Igor Murashkinbfc99152013-02-27 12:55:20 -08002256 Mutex::Autolock lock(mServiceLock);
2257
Ruben Brunkcc776712015-02-17 20:18:47 -08002258 {
2259 Mutex::Autolock lock(mStatusListenerLock);
2260 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002261 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2262 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2263 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002264 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002266 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002267 }
2268 }
2269
2270 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2271 __FUNCTION__, listener.get());
2272
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002273 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002274}
2275
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002276Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002277
2278 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002279 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2280
2281 if (parameters == NULL) {
2282 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002283 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002284 }
2285
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002286 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002287
2288 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002289 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002290 // Error logged by caller
2291 return ret;
2292 }
2293
2294 String8 shimParamsString8 = shimParams.flatten();
2295 String16 shimParamsString16 = String16(shimParamsString8);
2296
2297 *parameters = shimParamsString16;
2298
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002299 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002300}
2301
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002302Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2303 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002304 ATRACE_CALL();
2305
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002306 const String8 id = String8(cameraId);
2307
2308 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002309
2310 switch (apiVersion) {
2311 case API_VERSION_1:
2312 case API_VERSION_2:
2313 break;
2314 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 String8 msg = String8::format("Unknown API version %d", apiVersion);
2316 ALOGE("%s: %s", __FUNCTION__, msg.string());
2317 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002318 }
2319
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002320 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002321 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002322 case CAMERA_DEVICE_API_VERSION_1_0:
2323 case CAMERA_DEVICE_API_VERSION_3_0:
2324 case CAMERA_DEVICE_API_VERSION_3_1:
2325 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002326 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2327 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 *isSupported = false;
2329 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002330 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2331 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002332 *isSupported = true;
2333 }
2334 break;
2335 case CAMERA_DEVICE_API_VERSION_3_2:
2336 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002337 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002338 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002339 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002340 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2341 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 *isSupported = true;
2343 break;
2344 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002345 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002346 ALOGE("%s: %s", __FUNCTION__, msg.string());
2347 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002348 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002349 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002350 String8 msg = String8::format("Unknown device version %x for device %s",
2351 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002352 ALOGE("%s: %s", __FUNCTION__, msg.string());
2353 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2354 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002355 }
2356
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002358}
2359
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002360Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2361 /*out*/ bool *isSupported) {
2362 ATRACE_CALL();
2363
2364 const String8 id = String8(cameraId);
2365
2366 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2367 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2368
2369 return Status::ok();
2370}
2371
Ruben Brunkcc776712015-02-17 20:18:47 -08002372void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002373 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002374 for (auto& i : mActiveClientManager.getAll()) {
2375 auto clientSp = i->getValue();
2376 if (clientSp.get() == client) {
2377 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002378 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002379 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002380 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002381}
2382
Ruben Brunkcc776712015-02-17 20:18:47 -08002383bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 bool ret = false;
2385 {
2386 // Acquire mServiceLock and prevent other clients from connecting
2387 std::unique_ptr<AutoConditionLock> lock =
2388 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002389
Igor Murashkin634a5152013-02-20 17:15:11 -08002390
Ruben Brunkcc776712015-02-17 20:18:47 -08002391 std::vector<sp<BasicClient>> evicted;
2392 for (auto& i : mActiveClientManager.getAll()) {
2393 auto clientSp = i->getValue();
2394 if (clientSp.get() == nullptr) {
2395 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2396 mActiveClientManager.remove(i);
2397 continue;
2398 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002399 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002400 mActiveClientManager.remove(i);
2401 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002402
Ruben Brunkcc776712015-02-17 20:18:47 -08002403 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002404 clientSp->notifyError(
2405 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002406 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002407 }
2408 }
2409
Ruben Brunkcc776712015-02-17 20:18:47 -08002410 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2411 // other clients from connecting in mServiceLockWrapper if held
2412 mServiceLock.unlock();
2413
Ruben Brunk36597b22015-03-20 22:15:57 -07002414 // Do not clear caller identity, remote caller should be client proccess
2415
Ruben Brunkcc776712015-02-17 20:18:47 -08002416 for (auto& i : evicted) {
2417 if (i.get() != nullptr) {
2418 i->disconnect();
2419 ret = true;
2420 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002421 }
2422
Ruben Brunkcc776712015-02-17 20:18:47 -08002423 // Reacquire mServiceLock
2424 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002425
Ruben Brunkcc776712015-02-17 20:18:47 -08002426 } // lock is destroyed, allow further connect calls
2427
2428 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002429}
2430
Ruben Brunkcc776712015-02-17 20:18:47 -08002431std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2432 const String8& cameraId) const {
2433 std::shared_ptr<CameraState> state;
2434 {
2435 Mutex::Autolock lock(mCameraStatesLock);
2436 auto iter = mCameraStates.find(cameraId);
2437 if (iter != mCameraStates.end()) {
2438 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 }
2440 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002441 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442}
2443
Ruben Brunkcc776712015-02-17 20:18:47 -08002444sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2445 // Remove from active clients list
2446 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2447 if (clientDescriptorPtr == nullptr) {
2448 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2449 cameraId.string());
2450 return sp<BasicClient>{nullptr};
2451 }
2452
2453 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002454}
2455
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002456void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002457 // Acquire mServiceLock and prevent other clients from connecting
2458 std::unique_ptr<AutoConditionLock> lock =
2459 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2460
Ruben Brunk6267b532015-04-30 17:44:07 -07002461 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002462 for (size_t i = 0; i < newUserIds.size(); i++) {
2463 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002464 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002465 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002466 return;
2467 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002468 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002469 }
2470
Ruben Brunka8ca9152015-04-07 14:23:40 -07002471
Ruben Brunk6267b532015-04-30 17:44:07 -07002472 if (newAllowedUsers == mAllowedUsers) {
2473 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2474 return;
2475 }
2476
2477 logUserSwitch(mAllowedUsers, newAllowedUsers);
2478
2479 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002480
2481 // Current user has switched, evict all current clients.
2482 std::vector<sp<BasicClient>> evicted;
2483 for (auto& i : mActiveClientManager.getAll()) {
2484 auto clientSp = i->getValue();
2485
2486 if (clientSp.get() == nullptr) {
2487 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2488 continue;
2489 }
2490
Ruben Brunk6267b532015-04-30 17:44:07 -07002491 // Don't evict clients that are still allowed.
2492 uid_t clientUid = clientSp->getClientUid();
2493 userid_t clientUserId = multiuser_get_user_id(clientUid);
2494 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2495 continue;
2496 }
2497
Ruben Brunk36597b22015-03-20 22:15:57 -07002498 evicted.push_back(clientSp);
2499
2500 String8 curTime = getFormattedCurrentTime();
2501
2502 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2503 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002504
Ruben Brunk36597b22015-03-20 22:15:57 -07002505 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002506 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002507 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2508 " to user switch.", i->getKey().string(),
2509 String8{clientSp->getPackageName()}.string(),
2510 i->getOwnerId(), i->getPriority().getScore(),
2511 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002512
2513 }
2514
2515 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2516 // blocking other clients from connecting in mServiceLockWrapper if held.
2517 mServiceLock.unlock();
2518
2519 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002520 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002521
2522 for (auto& i : evicted) {
2523 i->disconnect();
2524 }
2525
Jayant Chowdhary12361932018-08-27 14:46:13 -07002526 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002527
2528 // Reacquire mServiceLock
2529 mServiceLock.lock();
2530}
Ruben Brunkcc776712015-02-17 20:18:47 -08002531
Ruben Brunka8ca9152015-04-07 14:23:40 -07002532void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002533 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002534 Mutex::Autolock l(mLogLock);
2535 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536}
2537
Ruben Brunka8ca9152015-04-07 14:23:40 -07002538void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002539 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002540 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002541 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002542 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002543}
2544
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002545void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2546 const char* clientPackage) {
2547 // Log the clients evicted
2548 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2549 cameraId, clientPackage, clientPid));
2550}
2551
Ruben Brunka8ca9152015-04-07 14:23:40 -07002552void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002553 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002554 // Log the clients evicted
2555 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002556 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002557}
2558
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002559void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2560 const char* clientPackage) {
2561 // Log the clients evicted
2562 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2563 clientPackage, clientPid));
2564}
2565
Ruben Brunka8ca9152015-04-07 14:23:40 -07002566void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002567 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002568 // Log the client rejected
2569 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002570 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002571}
2572
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002573void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2574 // Log torch event
2575 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2576 torchState, clientPid));
2577}
2578
Ruben Brunk6267b532015-04-30 17:44:07 -07002579void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2580 const std::set<userid_t>& newUserIds) {
2581 String8 newUsers = toString(newUserIds);
2582 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002583 if (oldUsers.size() == 0) {
2584 oldUsers = "<None>";
2585 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002586 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002587 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002588 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002589}
2590
2591void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2592 // Log the device removal
2593 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2594}
2595
2596void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2597 // Log the device removal
2598 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2599}
2600
2601void CameraService::logClientDied(int clientPid, const char* reason) {
2602 // Log the device removal
2603 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002604}
2605
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002606void CameraService::logServiceError(const char* msg, int errorCode) {
2607 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002608 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002609}
2610
Ruben Brunk36597b22015-03-20 22:15:57 -07002611status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2612 uint32_t flags) {
2613
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 // Permission checks
2615 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002616 case SHELL_COMMAND_TRANSACTION: {
2617 int in = data.readFileDescriptor();
2618 int out = data.readFileDescriptor();
2619 int err = data.readFileDescriptor();
2620 int argc = data.readInt32();
2621 Vector<String16> args;
2622 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2623 args.add(data.readString16());
2624 }
2625 sp<IBinder> unusedCallback;
2626 sp<IResultReceiver> resultReceiver;
2627 status_t status;
2628 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2629 return status;
2630 }
2631 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2632 return status;
2633 }
2634 status = shellCommand(in, out, err, args);
2635 if (resultReceiver != nullptr) {
2636 resultReceiver->send(status);
2637 }
2638 return NO_ERROR;
2639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 }
2641
2642 return BnCameraService::onTransact(code, data, reply, flags);
2643}
2644
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645// We share the media players for shutter and recording sound for all clients.
2646// A reference count is kept to determine when we will actually release the
2647// media players.
2648
Jaekyun Seokef498052018-03-23 13:09:44 +09002649sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2650 sp<MediaPlayer> mp = new MediaPlayer();
2651 status_t error;
2652 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002653 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002654 error = mp->prepare();
2655 }
2656 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002657 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002658 mp->disconnect();
2659 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002660 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 }
2662 return mp;
2663}
2664
username5755fea2018-12-27 09:48:08 +08002665void CameraService::increaseSoundRef() {
2666 Mutex::Autolock lock(mSoundLock);
2667 mSoundRef++;
2668}
2669
2670void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002671 ATRACE_CALL();
2672
username5755fea2018-12-27 09:48:08 +08002673 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2674 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2675 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2676 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2677 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2678 }
2679 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2680 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2681 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2682 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002683 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002684 }
2685 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2686 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2687 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2688 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2689 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002690 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691}
2692
username5755fea2018-12-27 09:48:08 +08002693void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002695 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 if (--mSoundRef) return;
2697
2698 for (int i = 0; i < NUM_SOUNDS; i++) {
2699 if (mSoundPlayer[i] != 0) {
2700 mSoundPlayer[i]->disconnect();
2701 mSoundPlayer[i].clear();
2702 }
2703 }
2704}
2705
2706void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002707 ATRACE_CALL();
2708
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 LOG1("playSound(%d)", kind);
2710 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002711 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 sp<MediaPlayer> player = mSoundPlayer[kind];
2713 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002714 player->seekTo(0);
2715 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 }
2717}
2718
2719// ----------------------------------------------------------------------------
2720
2721CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002722 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002723 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002724 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002725 const String8& cameraIdStr,
2726 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002727 int clientPid, uid_t clientUid,
2728 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002729 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002730 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002731 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002732 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002733 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002734 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002735 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002736{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002737 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002738 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002740 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741
username5755fea2018-12-27 09:48:08 +08002742 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002743
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002744 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745}
2746
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747// tear down the client
2748CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002749 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002750 mDestructionStarted = true;
2751
username5755fea2018-12-27 09:48:08 +08002752 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002753 // unconditionally disconnect. function is idempotent
2754 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755}
2756
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002757sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2758
Igor Murashkin634a5152013-02-20 17:15:11 -08002759CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002760 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002761 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002762 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002763 int clientPid, uid_t clientUid,
2764 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002765 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002766 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002767 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002768 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002769 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002770 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002771 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002772{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002773 if (sCameraService == nullptr) {
2774 sCameraService = cameraService;
2775 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002776 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002777 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002778
2779 // In some cases the calling code has no access to the package it runs under.
2780 // For example, NDK camera API.
2781 // In this case we will get the packages for the calling UID and pick the first one
2782 // for attributing the app op. This will work correctly for runtime permissions
2783 // as for legacy apps we will toggle the app op for all packages in the UID.
2784 // The caveat is that the operation may be attributed to the wrong package and
2785 // stats based on app ops may be slightly off.
2786 if (mClientPackageName.size() <= 0) {
2787 sp<IServiceManager> sm = defaultServiceManager();
2788 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2789 if (binder == 0) {
2790 ALOGE("Cannot get permission service");
2791 // Leave mClientPackageName unchanged (empty) and the further interaction
2792 // with camera will fail in BasicClient::startCameraOps
2793 return;
2794 }
2795
2796 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2797 Vector<String16> packages;
2798
2799 permCtrl->getPackagesForUid(mClientUid, packages);
2800
2801 if (packages.isEmpty()) {
2802 ALOGE("No packages for calling UID");
2803 // Leave mClientPackageName unchanged (empty) and the further interaction
2804 // with camera will fail in BasicClient::startCameraOps
2805 return;
2806 }
2807 mClientPackageName = packages[0];
2808 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002809 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002810 mAppOpsManager = std::make_unique<AppOpsManager>();
2811 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002812
2813 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002814}
2815
2816CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002817 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002818 mDestructionStarted = true;
2819}
2820
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002821binder::Status CameraService::BasicClient::disconnect() {
2822 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002823 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002824 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002825 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002826 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002827
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002828 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002829 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002830 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2831 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002832
2833 sp<IBinder> remote = getRemote();
2834 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002835 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002836 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002837
2838 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002839 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002840 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2841 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2842 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002843
Igor Murashkincba2c162013-03-20 15:56:31 -07002844 // client shouldn't be able to call into us anymore
2845 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002846
2847 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002848}
2849
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002850status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2851 // No dumping of clients directly over Binder,
2852 // must go through CameraService::dump
2853 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002854 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002855 return OK;
2856}
2857
Ruben Brunkcc776712015-02-17 20:18:47 -08002858String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002859 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002860}
2861
2862
2863int CameraService::BasicClient::getClientPid() const {
2864 return mClientPid;
2865}
2866
Ruben Brunk6267b532015-04-30 17:44:07 -07002867uid_t CameraService::BasicClient::getClientUid() const {
2868 return mClientUid;
2869}
2870
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002871bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2872 // Defaults to API2.
2873 return level == API_2;
2874}
2875
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002876status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002877 {
2878 Mutex::Autolock l(mAudioRestrictionLock);
2879 mAudioRestriction = mode;
2880 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002881 sCameraService->updateAudioRestriction();
2882 return OK;
2883}
2884
2885int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002886 return sCameraService->updateAudioRestriction();
2887}
2888
2889int32_t CameraService::BasicClient::getAudioRestriction() const {
2890 Mutex::Autolock l(mAudioRestrictionLock);
2891 return mAudioRestriction;
2892}
2893
2894bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2895 switch (mode) {
2896 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2897 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2898 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2899 return true;
2900 default:
2901 return false;
2902 }
2903}
2904
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002905status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002906 ATRACE_CALL();
2907
Igor Murashkine6800ce2013-03-04 17:25:57 -08002908 {
2909 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002910 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002911 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002912 if (mAppOpsManager != nullptr) {
2913 // Notify app ops that the camera is not available
2914 mOpsCallback = new OpsCallback(this);
2915 int32_t res;
2916 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2917 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002918 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2919 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2920 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002921
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002922 if (res == AppOpsManager::MODE_ERRORED) {
2923 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2924 mCameraIdStr.string(), String8(mClientPackageName).string());
2925 return PERMISSION_DENIED;
2926 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002927
Shuzhen Wang2c656792020-04-13 17:36:49 -07002928 // If the calling Uid is trusted (a native service), the AppOpsManager could
2929 // return MODE_IGNORED. Do not treat such case as error.
2930 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002931 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2932 mCameraIdStr.string(), String8(mClientPackageName).string());
2933 // Return the same error as for device policy manager rejection
2934 return -EACCES;
2935 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002936 }
2937
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002938 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002939
2940 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002941 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002942
Emilian Peev573291c2018-02-10 02:10:56 +00002943 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2944 if (canCastToApiClient(API_2)) {
2945 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2946 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002947 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002948 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002949 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002950
Emilian Peev53722fa2019-02-22 17:47:20 -08002951 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2952
Shuzhen Wang695044d2020-03-06 09:02:23 -08002953 // Notify listeners of camera open/close status
2954 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2955
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002956 return OK;
2957}
2958
2959status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002960 ATRACE_CALL();
2961
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002962 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002963 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002964 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002965 if (mAppOpsManager != nullptr) {
2966 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002967 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002968 mOpsActive = false;
2969 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002970 // This function is called when a client disconnects. This should
2971 // release the camera, but actually only if it was in a proper
2972 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002973 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002974 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002975
Ruben Brunkcc776712015-02-17 20:18:47 -08002976 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002977 sCameraService->updateStatus(StatusInternal::PRESENT,
2978 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002979
Emilian Peev573291c2018-02-10 02:10:56 +00002980 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2981 if (canCastToApiClient(API_2)) {
2982 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2983 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002984 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002985 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002986 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002987 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002988 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002989 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2990 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002991 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002992 mOpsCallback.clear();
2993
Emilian Peev53722fa2019-02-22 17:47:20 -08002994 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2995
Shuzhen Wang695044d2020-03-06 09:02:23 -08002996 // Notify listeners of camera open/close status
2997 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2998
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002999 return OK;
3000}
3001
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003002void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003003 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003004 if (mAppOpsManager == nullptr) {
3005 return;
3006 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003007 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003008 if (op != AppOpsManager::OP_CAMERA) {
3009 ALOGW("Unexpected app ops notification received: %d", op);
3010 return;
3011 }
3012
3013 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003014 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003015 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003016 ALOGV("checkOp returns: %d, %s ", res,
3017 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3018 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3019 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3020 "UNKNOWN");
3021
3022 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003023 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003024 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003025 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003026 }
3027}
3028
Svet Ganova453d0d2018-01-11 15:37:58 -08003029void CameraService::BasicClient::block() {
3030 ATRACE_CALL();
3031
3032 // Reset the client PID to allow server-initiated disconnect,
3033 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003034 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003035 CaptureResultExtras resultExtras; // a dummy result (invalid)
3036 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3037 disconnect();
3038}
3039
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040// ----------------------------------------------------------------------------
3041
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003042void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003043 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003044 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003045 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003046 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3047 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3048 api1ErrorCode = CAMERA_ERROR_DISABLED;
3049 }
3050 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003051 } else {
3052 ALOGE("mRemoteCallback is NULL!!");
3053 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003054}
3055
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003056// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003057binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003058 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003059 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003060}
3061
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003062bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3063 return level == API_1;
3064}
3065
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003066CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3067 mClient(client) {
3068}
3069
3070void CameraService::Client::OpsCallback::opChanged(int32_t op,
3071 const String16& packageName) {
3072 sp<BasicClient> client = mClient.promote();
3073 if (client != NULL) {
3074 client->opChanged(op, packageName);
3075 }
3076}
3077
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003079// UidPolicy
3080// ----------------------------------------------------------------------------
3081
3082void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003083 Mutex::Autolock _l(mUidLock);
3084
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003085 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003086 status_t res = mAm.linkToDeath(this);
3087 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003088 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003089 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003090 ActivityManager::PROCESS_STATE_UNKNOWN,
3091 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003092 if (res == OK) {
3093 mRegistered = true;
3094 ALOGV("UidPolicy: Registered with ActivityManager");
3095 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003096}
3097
3098void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003099 Mutex::Autolock _l(mUidLock);
3100
Steven Moreland2f348142019-07-02 15:59:07 -07003101 mAm.unregisterUidObserver(this);
3102 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003103 mRegistered = false;
3104 mActiveUids.clear();
3105 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003106}
3107
3108void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3109 onUidIdle(uid, disabled);
3110}
3111
3112void CameraService::UidPolicy::onUidActive(uid_t uid) {
3113 Mutex::Autolock _l(mUidLock);
3114 mActiveUids.insert(uid);
3115}
3116
3117void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3118 bool deleted = false;
3119 {
3120 Mutex::Autolock _l(mUidLock);
3121 if (mActiveUids.erase(uid) > 0) {
3122 deleted = true;
3123 }
3124 }
3125 if (deleted) {
3126 sp<CameraService> service = mService.promote();
3127 if (service != nullptr) {
3128 service->blockClientsForUid(uid);
3129 }
3130 }
3131}
3132
Emilian Peev53722fa2019-02-22 17:47:20 -08003133void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003134 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003135 bool procStateChange = false;
3136 {
3137 Mutex::Autolock _l(mUidLock);
3138 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3139 (mMonitoredUids[uid].first != procState)) {
3140 mMonitoredUids[uid].first = procState;
3141 procStateChange = true;
3142 }
3143 }
3144
3145 if (procStateChange) {
3146 sp<CameraService> service = mService.promote();
3147 if (service != nullptr) {
3148 service->notifyMonitoredUids();
3149 }
3150 }
3151}
3152
3153void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3154 Mutex::Autolock _l(mUidLock);
3155 auto it = mMonitoredUids.find(uid);
3156 if (it != mMonitoredUids.end()) {
3157 it->second.second++;
3158 } else {
3159 mMonitoredUids.emplace(
3160 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3161 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3162 }
3163}
3164
3165void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3166 Mutex::Autolock _l(mUidLock);
3167 auto it = mMonitoredUids.find(uid);
3168 if (it != mMonitoredUids.end()) {
3169 it->second.second--;
3170 if (it->second.second == 0) {
3171 mMonitoredUids.erase(it);
3172 }
3173 } else {
3174 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3175 }
3176}
3177
Svet Ganov7b4ab782018-03-25 12:48:10 -07003178bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003179 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003180 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003181}
3182
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003183static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3184static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003185
Svet Ganov7b4ab782018-03-25 12:48:10 -07003186bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003187 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003188 // If activity manager is unreachable, assume everything is active
3189 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003190 return true;
3191 }
3192 auto it = mOverrideUids.find(uid);
3193 if (it != mOverrideUids.end()) {
3194 return it->second;
3195 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003196 bool active = mActiveUids.find(uid) != mActiveUids.end();
3197 if (!active) {
3198 // We want active UIDs to always access camera with their first attempt since
3199 // there is no guarantee the app is robustly written and would retry getting
3200 // the camera on failure. The inverse case is not a problem as we would take
3201 // camera away soon once we get the callback that the uid is no longer active.
3202 ActivityManager am;
3203 // Okay to access with a lock held as UID changes are dispatched without
3204 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003205 int64_t startTimeMillis = 0;
3206 do {
3207 // TODO: Fix this b/109950150!
3208 // Okay this is a hack. There is a race between the UID turning active and
3209 // activity being resumed. The proper fix is very risky, so we temporary add
3210 // some polling which should happen pretty rarely anyway as the race is hard
3211 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003212 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003213 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003214 if (active) {
3215 break;
3216 }
3217 if (startTimeMillis <= 0) {
3218 startTimeMillis = uptimeMillis();
3219 }
3220 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003221 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003222 if (remainingTimeMillis <= 0) {
3223 break;
3224 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003225 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3226
3227 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003228 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003229 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003230 } while (true);
3231
Svet Ganov7b4ab782018-03-25 12:48:10 -07003232 if (active) {
3233 // Now that we found out the UID is actually active, cache that
3234 mActiveUids.insert(uid);
3235 }
3236 }
3237 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003238}
3239
Varun Shahb42f1eb2019-04-16 14:45:13 -07003240int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3241 Mutex::Autolock _l(mUidLock);
3242 return getProcStateLocked(uid);
3243}
3244
3245int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3246 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3247 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3248 procState = mMonitoredUids[uid].first;
3249 }
3250 return procState;
3251}
3252
Svet Ganov7b4ab782018-03-25 12:48:10 -07003253void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3254 String16 callingPackage, bool active) {
3255 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003256}
3257
Svet Ganov7b4ab782018-03-25 12:48:10 -07003258void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3259 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003260}
3261
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003262void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3263 Mutex::Autolock _l(mUidLock);
3264 ALOGV("UidPolicy: ActivityManager has died");
3265 mRegistered = false;
3266 mActiveUids.clear();
3267}
3268
Svet Ganov7b4ab782018-03-25 12:48:10 -07003269void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3270 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003271 bool wasActive = false;
3272 bool isActive = false;
3273 {
3274 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003275 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003276 mOverrideUids.erase(uid);
3277 if (insert) {
3278 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3279 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003280 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003281 }
3282 if (wasActive != isActive && !isActive) {
3283 sp<CameraService> service = mService.promote();
3284 if (service != nullptr) {
3285 service->blockClientsForUid(uid);
3286 }
3287 }
3288}
3289
3290// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003291// SensorPrivacyPolicy
3292// ----------------------------------------------------------------------------
3293void CameraService::SensorPrivacyPolicy::registerSelf() {
3294 Mutex::Autolock _l(mSensorPrivacyLock);
3295 if (mRegistered) {
3296 return;
3297 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003298 mSpm.addSensorPrivacyListener(this);
3299 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3300 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003301 if (res == OK) {
3302 mRegistered = true;
3303 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3304 }
3305}
3306
3307void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3308 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003309 mSpm.removeSensorPrivacyListener(this);
3310 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003311 mRegistered = false;
3312 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3313}
3314
3315bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3316 Mutex::Autolock _l(mSensorPrivacyLock);
3317 return mSensorPrivacyEnabled;
3318}
3319
3320binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3321 {
3322 Mutex::Autolock _l(mSensorPrivacyLock);
3323 mSensorPrivacyEnabled = enabled;
3324 }
3325 // if sensor privacy is enabled then block all clients from accessing the camera
3326 if (enabled) {
3327 sp<CameraService> service = mService.promote();
3328 if (service != nullptr) {
3329 service->blockAllClients();
3330 }
3331 }
3332 return binder::Status::ok();
3333}
3334
3335void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3336 Mutex::Autolock _l(mSensorPrivacyLock);
3337 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3338 mRegistered = false;
3339}
3340
3341// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003342// CameraState
3343// ----------------------------------------------------------------------------
3344
3345CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003346 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3347 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3348 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003349
3350CameraService::CameraState::~CameraState() {}
3351
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003352CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003353 Mutex::Autolock lock(mStatusLock);
3354 return mStatus;
3355}
3356
Shuzhen Wang43858162020-01-10 13:42:15 -08003357std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3358 Mutex::Autolock lock(mStatusLock);
3359 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3360 return res;
3361}
3362
Ruben Brunkcc776712015-02-17 20:18:47 -08003363CameraParameters CameraService::CameraState::getShimParams() const {
3364 return mShimParams;
3365}
3366
3367void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3368 mShimParams = params;
3369}
3370
3371int CameraService::CameraState::getCost() const {
3372 return mCost;
3373}
3374
3375std::set<String8> CameraService::CameraState::getConflicting() const {
3376 return mConflicting;
3377}
3378
3379String8 CameraService::CameraState::getId() const {
3380 return mId;
3381}
3382
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003383SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3384 return mSystemCameraKind;
3385}
3386
Shuzhen Wang43858162020-01-10 13:42:15 -08003387bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3388 Mutex::Autolock lock(mStatusLock);
3389 auto result = mUnavailablePhysicalIds.insert(physicalId);
3390 return result.second;
3391}
3392
3393bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3394 Mutex::Autolock lock(mStatusLock);
3395 auto count = mUnavailablePhysicalIds.erase(physicalId);
3396 return count > 0;
3397}
3398
Ruben Brunkcc776712015-02-17 20:18:47 -08003399// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003400// ClientEventListener
3401// ----------------------------------------------------------------------------
3402
3403void CameraService::ClientEventListener::onClientAdded(
3404 const resource_policy::ClientDescriptor<String8,
3405 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003406 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003407 if (basicClient.get() != nullptr) {
3408 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3409 notifier.noteStartCamera(descriptor.getKey(),
3410 static_cast<int>(basicClient->getClientUid()));
3411 }
3412}
3413
3414void CameraService::ClientEventListener::onClientRemoved(
3415 const resource_policy::ClientDescriptor<String8,
3416 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003417 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003418 if (basicClient.get() != nullptr) {
3419 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3420 notifier.noteStopCamera(descriptor.getKey(),
3421 static_cast<int>(basicClient->getClientUid()));
3422 }
3423}
3424
3425
3426// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003427// CameraClientManager
3428// ----------------------------------------------------------------------------
3429
Ruben Brunk99e69712015-05-26 17:25:07 -07003430CameraService::CameraClientManager::CameraClientManager() {
3431 setListener(std::make_shared<ClientEventListener>());
3432}
3433
Ruben Brunkcc776712015-02-17 20:18:47 -08003434CameraService::CameraClientManager::~CameraClientManager() {}
3435
3436sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3437 const String8& id) const {
3438 auto descriptor = get(id);
3439 if (descriptor == nullptr) {
3440 return sp<BasicClient>{nullptr};
3441 }
3442 return descriptor->getValue();
3443}
3444
3445String8 CameraService::CameraClientManager::toString() const {
3446 auto all = getAll();
3447 String8 ret("[");
3448 bool hasAny = false;
3449 for (auto& i : all) {
3450 hasAny = true;
3451 String8 key = i->getKey();
3452 int32_t cost = i->getCost();
3453 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003454 int32_t score = i->getPriority().getScore();
3455 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003456 auto conflicting = i->getConflicting();
3457 auto clientSp = i->getValue();
3458 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003459 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003460 if (clientSp.get() != nullptr) {
3461 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003462 uid_t clientUid = clientSp->getClientUid();
3463 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003464 }
Emilian Peev8131a262017-02-01 12:33:43 +00003465 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3466 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003467
Ruben Brunk6267b532015-04-30 17:44:07 -07003468 if (clientSp.get() != nullptr) {
3469 ret.appendFormat("User Id: %d, ", clientUserId);
3470 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003471 if (packageName.size() != 0) {
3472 ret.appendFormat("Client Package Name: %s", packageName.string());
3473 }
3474
3475 ret.append(", Conflicting Client Devices: {");
3476 for (auto& j : conflicting) {
3477 ret.appendFormat("%s, ", j.string());
3478 }
3479 ret.append("})");
3480 }
3481 if (hasAny) ret.append("\n");
3482 ret.append("]\n");
3483 return ret;
3484}
3485
3486CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3487 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003488 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3489 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003490
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003491 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003492 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3493 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3494
Ruben Brunkcc776712015-02-17 20:18:47 -08003495 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003496 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003497}
3498
3499CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3500 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3501 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003502 partial->getConflicting(), partial->getPriority().getScore(),
3503 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003504}
3505
3506// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507
3508static const int kDumpLockRetries = 50;
3509static const int kDumpLockSleep = 60000;
3510
3511static bool tryLock(Mutex& mutex)
3512{
3513 bool locked = false;
3514 for (int i = 0; i < kDumpLockRetries; ++i) {
3515 if (mutex.tryLock() == NO_ERROR) {
3516 locked = true;
3517 break;
3518 }
3519 usleep(kDumpLockSleep);
3520 }
3521 return locked;
3522}
3523
3524status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003525 ATRACE_CALL();
3526
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003527 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003528 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003529 CameraThreadState::getCallingPid(),
3530 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003531 return NO_ERROR;
3532 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003533 bool locked = tryLock(mServiceLock);
3534 // failed to lock - CameraService is probably deadlocked
3535 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003536 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003537 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003538
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003539 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003540 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003541
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003542 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003543 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003544
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003545 if (locked) mServiceLock.unlock();
3546 return NO_ERROR;
3547 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003548 dprintf(fd, "\n== Service global info: ==\n\n");
3549 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003550 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003551 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3552 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003553 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3554 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3555 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003556 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003557 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3558 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003559
3560 dumpEventLog(fd);
3561
3562 bool stateLocked = tryLock(mCameraStatesLock);
3563 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003564 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003565 }
3566
Emilian Peevbd8c5032018-02-14 23:05:40 +00003567 int argSize = args.size();
3568 for (int i = 0; i < argSize; i++) {
3569 if (args[i] == TagMonitor::kMonitorOption) {
3570 if (i + 1 < argSize) {
3571 mMonitorTags = String8(args[i + 1]);
3572 }
3573 break;
3574 }
3575 }
3576
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003577 for (auto& state : mCameraStates) {
3578 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003579
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003580 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003581
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003582 CameraParameters p = state.second->getShimParams();
3583 if (!p.isEmpty()) {
3584 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3585 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003586 }
3587
3588 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003589 if (clientDescriptor != nullptr) {
3590 dprintf(fd, " Device %s is open. Client instance dump:\n",
3591 cameraId.string());
3592 dprintf(fd, " Client priority score: %d state: %d\n",
3593 clientDescriptor->getPriority().getScore(),
3594 clientDescriptor->getPriority().getState());
3595 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3596
3597 auto client = clientDescriptor->getValue();
3598 dprintf(fd, " Client package: %s\n",
3599 String8(client->getPackageName()).string());
3600
3601 client->dumpClient(fd, args);
3602 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003603 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003604 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003605 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003606
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003607 }
3608
3609 if (stateLocked) mCameraStatesLock.unlock();
3610
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003611 if (locked) mServiceLock.unlock();
3612
Emilian Peevf53f66e2017-04-11 14:29:43 +01003613 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003614
3615 dprintf(fd, "\n== Vendor tags: ==\n\n");
3616
3617 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3618 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003619 sp<VendorTagDescriptorCache> cache =
3620 VendorTagDescriptorCache::getGlobalVendorTagCache();
3621 if (cache == NULL) {
3622 dprintf(fd, "No vendor tags.\n");
3623 } else {
3624 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3625 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003626 } else {
3627 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3628 }
3629
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003630 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003631 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003632 camera3::CameraTraces::dump(fd, args);
3633
3634 // Process dump arguments, if any
3635 int n = args.size();
3636 String16 verboseOption("-v");
3637 String16 unreachableOption("--unreachable");
3638 for (int i = 0; i < n; i++) {
3639 if (args[i] == verboseOption) {
3640 // change logging level
3641 if (i + 1 >= n) continue;
3642 String8 levelStr(args[i+1]);
3643 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003644 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003645 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003646 } else if (args[i] == unreachableOption) {
3647 // Dump memory analysis
3648 // TODO - should limit be an argument parameter?
3649 UnreachableMemoryInfo info;
3650 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3651 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003652 dprintf(fd, "\n== Unable to dump unreachable memory. "
3653 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003654 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003655 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003656 std::string s = info.ToString(/*log_contents*/ true);
3657 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658 }
3659 }
3660 }
3661 return NO_ERROR;
3662}
3663
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003664void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003665 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003666
3667 Mutex::Autolock l(mLogLock);
3668 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003669 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003670 }
3671
3672 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003673 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003674 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003675 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003676 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003677 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003678}
3679
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003680void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003681 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003682 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3683 if (mTorchClientMap[i] == who) {
3684 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003685 String8 cameraId = mTorchClientMap.keyAt(i);
3686 status_t res = mFlashlight->setTorchMode(cameraId, false);
3687 if (res) {
3688 ALOGE("%s: torch client died but couldn't turn off torch: "
3689 "%s (%d)", __FUNCTION__, strerror(-res), res);
3690 return;
3691 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003692 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003693 break;
3694 }
3695 }
3696}
3697
Ruben Brunkcc776712015-02-17 20:18:47 -08003698/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003699
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003700 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003701 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3702 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003703 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003704 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003705 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003706
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003707 // check torch client
3708 handleTorchClientBinderDied(who);
3709
3710 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003711 if(!evictClientIdByRemote(who)) {
3712 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003713 return;
3714 }
3715
Ruben Brunkcc776712015-02-17 20:18:47 -08003716 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3717 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003718}
3719
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003720void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003722}
3723
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003724void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3725 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003726 // Do not lock mServiceLock here or can get into a deadlock from
3727 // connect() -> disconnect -> updateStatus
3728
3729 auto state = getCameraState(cameraId);
3730
3731 if (state == nullptr) {
3732 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3733 cameraId.string());
3734 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003735 }
3736
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003737 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3738 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3739 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3740 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3741 return;
3742 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003743 bool supportsHAL3 = false;
3744 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3745 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3746 // mInterfaceMutex together, which can lead to deadlocks)
3747 binder::Status sRet =
3748 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3749 &supportsHAL3);
3750 if (!sRet.isOk()) {
3751 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3752 __FUNCTION__, cameraId.string());
3753 return;
3754 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003755 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003756 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003757 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003758 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003759
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003760 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003761 // Update torch status if it has a flash unit.
3762 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003763 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003764 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3765 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003766 TorchModeStatus newTorchStatus =
3767 status == StatusInternal::PRESENT ?
3768 TorchModeStatus::AVAILABLE_OFF :
3769 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003770 if (torchStatus != newTorchStatus) {
3771 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3772 }
3773 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003774 }
3775
3776 Mutex::Autolock lock(mStatusListenerLock);
3777
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003778 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003779
Ruben Brunkcc776712015-02-17 20:18:47 -08003780 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003781 bool isVendorListener = listener->isVendorListener();
3782 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3783 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003784 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003785 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003786 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003787 continue;
3788 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003789 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003790 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003791 }
3792 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003793}
3794
Shuzhen Wang695044d2020-03-06 09:02:23 -08003795void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3796 const String16& clientPackageName) {
3797 Mutex::Autolock lock(mStatusListenerLock);
3798
3799 for (const auto& it : mListenerList) {
3800 if (!it->isOpenCloseCallbackAllowed()) {
3801 continue;
3802 }
3803
3804 binder::Status ret;
3805 String16 cameraId64(cameraId);
3806 if (open) {
3807 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3808 } else {
3809 ret = it->getListener()->onCameraClosed(cameraId64);
3810 }
3811 if (!ret.isOk()) {
3812 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3813 ret.exceptionCode());
3814 }
3815 }
3816}
3817
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003818template<class Func>
3819void CameraService::CameraState::updateStatus(StatusInternal status,
3820 const String8& cameraId,
3821 std::initializer_list<StatusInternal> rejectSourceStates,
3822 Func onStatusUpdatedLocked) {
3823 Mutex::Autolock lock(mStatusLock);
3824 StatusInternal oldStatus = mStatus;
3825 mStatus = status;
3826
3827 if (oldStatus == status) {
3828 return;
3829 }
3830
3831 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3832 cameraId.string(), oldStatus, status);
3833
3834 if (oldStatus == StatusInternal::NOT_PRESENT &&
3835 (status != StatusInternal::PRESENT &&
3836 status != StatusInternal::ENUMERATING)) {
3837
3838 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3839 __FUNCTION__);
3840 mStatus = oldStatus;
3841 return;
3842 }
3843
3844 /**
3845 * Sometimes we want to conditionally do a transition.
3846 * For example if a client disconnects, we want to go to PRESENT
3847 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3848 */
3849 for (auto& rejectStatus : rejectSourceStates) {
3850 if (oldStatus == rejectStatus) {
3851 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3852 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3853 mStatus = oldStatus;
3854 return;
3855 }
3856 }
3857
3858 onStatusUpdatedLocked(cameraId, status);
3859}
3860
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003861void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003862 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003863 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3864 if (proxyBinder == nullptr) return;
3865 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003866 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003867}
3868
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003869status_t CameraService::getTorchStatusLocked(
3870 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003871 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003872 if (!status) {
3873 return BAD_VALUE;
3874 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003875 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3876 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003877 // invalid camera ID or the camera doesn't have a flash unit
3878 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003879 }
3880
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003881 *status = mTorchStatusMap.valueAt(index);
3882 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003883}
3884
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003885status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003886 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003887 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3888 if (index == NAME_NOT_FOUND) {
3889 return BAD_VALUE;
3890 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003891 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003892
3893 return OK;
3894}
3895
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003896void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId,
3897 SystemCameraKind deviceKind) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003898 Mutex::Autolock lock(mCameraStatesLock);
3899 for (const auto& state : mCameraStates) {
3900 std::vector<std::string> physicalCameraIds;
3901 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3902 // This is not a logical multi-camera.
3903 continue;
3904 }
3905 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3906 == physicalCameraIds.end()) {
3907 // cameraId is not a physical camera of this logical multi-camera.
3908 continue;
3909 }
3910
3911 String16 id16(state.first), physicalId16(cameraId);
3912 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003913 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3914 listener->getListenerPid(), listener->getListenerUid())) {
3915 ALOGV("Skipping discovery callback for system-only camera device %s",
3916 cameraId.c_str());
3917 continue;
3918 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003919 listener->getListener()->onPhysicalCameraStatusChanged(status,
3920 id16, physicalId16);
3921 }
3922 }
3923}
3924
Svet Ganova453d0d2018-01-11 15:37:58 -08003925void CameraService::blockClientsForUid(uid_t uid) {
3926 const auto clients = mActiveClientManager.getAll();
3927 for (auto& current : clients) {
3928 if (current != nullptr) {
3929 const auto basicClient = current->getValue();
3930 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3931 basicClient->block();
3932 }
3933 }
3934 }
3935}
3936
Michael Grooverd1d435a2018-12-18 17:39:42 -08003937void CameraService::blockAllClients() {
3938 const auto clients = mActiveClientManager.getAll();
3939 for (auto& current : clients) {
3940 if (current != nullptr) {
3941 const auto basicClient = current->getValue();
3942 if (basicClient.get() != nullptr) {
3943 basicClient->block();
3944 }
3945 }
3946 }
3947}
3948
Svet Ganova453d0d2018-01-11 15:37:58 -08003949// NOTE: This is a remote API - make sure all args are validated
3950status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3951 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3952 return PERMISSION_DENIED;
3953 }
3954 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3955 return BAD_VALUE;
3956 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003957 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003958 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003959 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003960 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003961 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003962 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003963 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3964 return handleSetRotateAndCrop(args);
3965 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3966 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003967 } else if (args.size() == 1 && args[0] == String16("help")) {
3968 printHelp(out);
3969 return NO_ERROR;
3970 }
3971 printHelp(err);
3972 return BAD_VALUE;
3973}
3974
3975status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003976 String16 packageName = args[1];
3977
Svet Ganova453d0d2018-01-11 15:37:58 -08003978 bool active = false;
3979 if (args[2] == String16("active")) {
3980 active = true;
3981 } else if ((args[2] != String16("idle"))) {
3982 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3983 return BAD_VALUE;
3984 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003985
3986 int userId = 0;
3987 if (args.size() >= 5 && args[3] == String16("--user")) {
3988 userId = atoi(String8(args[4]));
3989 }
3990
3991 uid_t uid;
3992 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3993 return BAD_VALUE;
3994 }
3995
3996 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003997 return NO_ERROR;
3998}
3999
4000status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004001 String16 packageName = args[1];
4002
4003 int userId = 0;
4004 if (args.size() >= 4 && args[2] == String16("--user")) {
4005 userId = atoi(String8(args[3]));
4006 }
4007
4008 uid_t uid;
4009 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004010 return BAD_VALUE;
4011 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004012
4013 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004014 return NO_ERROR;
4015}
4016
4017status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004018 String16 packageName = args[1];
4019
4020 int userId = 0;
4021 if (args.size() >= 4 && args[2] == String16("--user")) {
4022 userId = atoi(String8(args[3]));
4023 }
4024
4025 uid_t uid;
4026 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004027 return BAD_VALUE;
4028 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004029
4030 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004031 return dprintf(out, "active\n");
4032 } else {
4033 return dprintf(out, "idle\n");
4034 }
4035}
4036
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004037status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4038 int rotateValue = atoi(String8(args[1]));
4039 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4040 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4041 Mutex::Autolock lock(mServiceLock);
4042
4043 mOverrideRotateAndCropMode = rotateValue;
4044
4045 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4046
4047 const auto clients = mActiveClientManager.getAll();
4048 for (auto& current : clients) {
4049 if (current != nullptr) {
4050 const auto basicClient = current->getValue();
4051 if (basicClient.get() != nullptr) {
4052 basicClient->setRotateAndCropOverride(rotateValue);
4053 }
4054 }
4055 }
4056
4057 return OK;
4058}
4059
4060status_t CameraService::handleGetRotateAndCrop(int out) {
4061 Mutex::Autolock lock(mServiceLock);
4062
4063 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4064}
4065
Svet Ganova453d0d2018-01-11 15:37:58 -08004066status_t CameraService::printHelp(int out) {
4067 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004068 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4069 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4070 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004071 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4072 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4073 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004074 " help print this message\n");
4075}
4076
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004077int32_t CameraService::updateAudioRestriction() {
4078 Mutex::Autolock lock(mServiceLock);
4079 return updateAudioRestrictionLocked();
4080}
4081
4082int32_t CameraService::updateAudioRestrictionLocked() {
4083 int32_t mode = 0;
4084 // iterate through all active client
4085 for (const auto& i : mActiveClientManager.getAll()) {
4086 const auto clientSp = i->getValue();
4087 mode |= clientSp->getAudioRestriction();
4088 }
4089
4090 bool modeChanged = (mAudioRestriction != mode);
4091 mAudioRestriction = mode;
4092 if (modeChanged) {
4093 mAppOps.setCameraAudioRestriction(mode);
4094 }
4095 return mode;
4096}
4097
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098}; // namespace android