blob: 4e4fc4f40c1c7ae0e17f233e23fa759243b1f6d0 [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{});
499 // Ensure not in binder RPC so client disconnect PID checks work correctly
500 LOG_ALWAYS_FATAL_IF(CameraThreadState::getCallingPid() != getpid(),
501 "onDeviceStatusChanged must be called from the camera service process!");
502 clientToDisconnect->disconnect();
503 }
504}
505
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800506void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800507 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800508 Mutex::Autolock al(mTorchStatusMutex);
509 onTorchStatusChangedLocked(cameraId, newStatus);
510}
511
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800512void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 TorchModeStatus newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800514 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
515 __FUNCTION__, cameraId.string(), newStatus);
516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800518 status_t res = getTorchStatusLocked(cameraId, &status);
519 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700520 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
521 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800522 return;
523 }
524 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800525 return;
526 }
527
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800528 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800529 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800530 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
531 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800532 return;
533 }
534
Ruben Brunkcc776712015-02-17 20:18:47 -0800535 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700536 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700537 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700538 auto iter = mTorchUidMap.find(cameraId);
539 if (iter != mTorchUidMap.end()) {
540 int oldUid = iter->second.second;
541 int newUid = iter->second.first;
542 BatteryNotifier& notifier(BatteryNotifier::getInstance());
543 if (oldUid != newUid) {
544 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700546 notifier.noteFlashlightOff(cameraId, oldUid);
547 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800548 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700549 notifier.noteFlashlightOn(cameraId, newUid);
550 }
551 iter->second.second = newUid;
552 } else {
553 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800554 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700555 notifier.noteFlashlightOn(cameraId, oldUid);
556 } else {
557 notifier.noteFlashlightOff(cameraId, oldUid);
558 }
559 }
560 }
561 }
562
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800563 broadcastTorchModeStatus(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800564}
565
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700566static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
567 return checkPermission(sSystemCameraPermission, callingPid, callingUid) &&
568 checkPermission(sCameraPermission, callingPid, callingUid);
569}
570
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800571Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700572 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100573 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700574 bool hasSystemCameraPermissions =
575 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
576 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700577 switch (type) {
578 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700579 if (hasSystemCameraPermissions) {
580 *numCameras = static_cast<int>(mNormalDeviceIds.size());
581 } else {
582 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
583 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800584 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700585 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700586 if (hasSystemCameraPermissions) {
587 *numCameras = mNumberOfCameras;
588 } else {
589 *numCameras = mNumberOfCamerasWithoutSystemCamera;
590 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800591 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700592 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800593 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700594 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800595 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
596 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700597 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800598 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599}
600
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800601Status CameraService::getCameraInfo(int cameraId,
602 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700603 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100604 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700605 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
606 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
607 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
608 "characteristics for system only device %s: ", cameraIdStr.c_str());
609 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100610
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800611 if (!mInitialized) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800612 return STATUS_ERROR(ERROR_DISCONNECTED,
613 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700614 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700615 bool hasSystemCameraPermissions =
616 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
617 CameraThreadState::getCallingUid());
618 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
619 if (hasSystemCameraPermissions) {
620 cameraIdBound = mNumberOfCameras;
621 }
622 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800623 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
624 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 }
626
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800627 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800628 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700629 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100630 if (err != OK) {
631 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
632 "Error retrieving camera info from device %d: %s (%d)", cameraId,
633 strerror(-err), err);
Ruben Brunkcc776712015-02-17 20:18:47 -0800634 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100635
Ruben Brunkcc776712015-02-17 20:18:47 -0800636 return ret;
637}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700638
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800639std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700640 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
641 auto callingPid = CameraThreadState::getCallingPid();
642 auto callingUid = CameraThreadState::getCallingUid();
643 if (checkPermission(sSystemCameraPermission, callingPid, callingUid) ||
644 getpid() == callingPid) {
645 deviceIds = &mNormalDeviceIds;
646 }
647 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800648 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700649 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800650 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800651 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800652
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700653 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800654}
655
656String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
657 Mutex::Autolock lock(mServiceLock);
658 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800659}
660
661Status CameraService::getCameraCharacteristics(const String16& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800662 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700663 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700664 if (!cameraInfo) {
665 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800666 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700667 }
668
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800669 if (!mInitialized) {
670 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800671 return STATUS_ERROR(ERROR_DISCONNECTED,
672 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700673 }
674
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700675 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
676 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
677 "characteristics for system only device %s: ", String8(cameraId).string());
678 }
679
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800680 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800681
Emilian Peevf53f66e2017-04-11 14:29:43 +0100682 status_t res = mCameraProviderManager->getCameraCharacteristics(
683 String8(cameraId).string(), cameraInfo);
684 if (res != OK) {
685 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
686 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
687 strerror(-res), res);
Ruben Brunkb2119af2014-05-09 19:57:56 -0700688 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700689 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
690 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
691 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
692 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
693 "for device %s", String8(cameraId).string());
694 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700695 int callingPid = CameraThreadState::getCallingPid();
696 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100697 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700698 // If it's not calling from cameraserver, check the permission only if
699 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
700 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100701 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700702 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700703 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100704 res = cameraInfo->removePermissionEntries(
705 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
706 &tagsRemoved);
707 if (res != OK) {
708 cameraInfo->clear();
709 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
710 " characteristics needing camera permission for device %s: %s (%d)",
711 String8(cameraId).string(), strerror(-res), res);
712 }
713 }
714
715 if (!tagsRemoved.empty()) {
716 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
717 tagsRemoved.data(), tagsRemoved.size());
718 if (res != OK) {
719 cameraInfo->clear();
720 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
721 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
722 strerror(-res), res);
723 }
724 }
725
Zhijun He2b59be82013-09-25 10:14:30 -0700726 return ret;
727}
728
Ruben Brunkcc776712015-02-17 20:18:47 -0800729String8 CameraService::getFormattedCurrentTime() {
730 time_t now = time(nullptr);
731 char formattedTime[64];
732 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
733 return String8(formattedTime);
734}
735
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736Status CameraService::getCameraVendorTagDescriptor(
737 /*out*/
738 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700739 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800740 if (!mInitialized) {
741 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800742 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800743 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800744 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
745 if (globalDescriptor != nullptr) {
746 *desc = *(globalDescriptor.get());
747 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800748 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800749}
750
Emilian Peev71c73a22017-03-21 16:35:51 +0000751Status CameraService::getCameraVendorTagCache(
752 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
753 ATRACE_CALL();
754 if (!mInitialized) {
755 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
756 return STATUS_ERROR(ERROR_DISCONNECTED,
757 "Camera subsystem not available");
758 }
759 sp<VendorTagDescriptorCache> globalCache =
760 VendorTagDescriptorCache::getGlobalVendorTagCache();
761 if (globalCache != nullptr) {
762 *cache = *(globalCache.get());
763 }
764 return Status::ok();
765}
766
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800767int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700768 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800769
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800770 int deviceVersion = 0;
771
Emilian Peevf53f66e2017-04-11 14:29:43 +0100772 status_t res;
773 hardware::hidl_version maxVersion{0,0};
774 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
775 &maxVersion);
776 if (res != OK) return -1;
777 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800778
Emilian Peevf53f66e2017-04-11 14:29:43 +0100779 hardware::CameraInfo info;
780 if (facing) {
781 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800782 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100783 *facing = info.facing;
Igor Murashkin634a5152013-02-20 17:15:11 -0800784 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100785
Igor Murashkin634a5152013-02-20 17:15:11 -0800786 return deviceVersion;
787}
788
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800789Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700790 switch(err) {
791 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800792 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800793 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800794 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
795 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800796 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797 return STATUS_ERROR(ERROR_DISCONNECTED,
798 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700799 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
801 "Camera HAL encountered error %d: %s",
802 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700803 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800804}
805
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800807 const sp<IInterface>& cameraCb, const String16& packageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900808 const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800809 int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
810 int deviceVersion, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800811 /*out*/sp<BasicClient>* client) {
812
Ruben Brunkcc776712015-02-17 20:18:47 -0800813 if (halVersion < 0 || halVersion == deviceVersion) {
814 // Default path: HAL version is unspecified by caller, create CameraClient
815 // based on device version reported by the HAL.
816 switch(deviceVersion) {
817 case CAMERA_DEVICE_API_VERSION_1_0:
818 if (effectiveApiLevel == API_1) { // Camera1 API route
819 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800820 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800821 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700822 getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800823 } else { // Camera2 API route
824 ALOGW("Camera using old HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800825 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800826 "Camera device \"%s\" HAL version %d does not support camera2 API",
827 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800828 }
829 break;
Ruben Brunkcc776712015-02-17 20:18:47 -0800830 case CAMERA_DEVICE_API_VERSION_3_0:
831 case CAMERA_DEVICE_API_VERSION_3_1:
832 case CAMERA_DEVICE_API_VERSION_3_2:
833 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -0700834 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -0700835 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -0800836 case CAMERA_DEVICE_API_VERSION_3_6:
Ruben Brunkcc776712015-02-17 20:18:47 -0800837 if (effectiveApiLevel == API_1) { // Camera1 API route
838 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800839 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800840 cameraId, api1CameraId,
841 facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700842 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800843 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800844 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
845 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800846 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
847 cameraId, facing, clientPid, clientUid, servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800848 }
849 break;
850 default:
851 // Should not be reachable
852 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800853 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800854 "Camera device \"%s\" has unknown HAL version %d",
855 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800856 }
857 } else {
858 // A particular HAL version is requested by caller. Create CameraClient
859 // based on the requested HAL version.
860 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
861 halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
862 // Only support higher HAL version device opened as HAL1.0 device.
863 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800864 *client = new CameraClient(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800865 api1CameraId, facing, clientPid, clientUid,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700866 servicePid);
Ruben Brunkcc776712015-02-17 20:18:47 -0800867 } else {
868 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
869 ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
870 " opened as HAL %x device", halVersion, deviceVersion,
871 CAMERA_DEVICE_API_VERSION_1_0);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800872 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800873 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
874 cameraId.string(), deviceVersion, halVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800875 }
876 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800877 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800878}
879
Ruben Brunk6267b532015-04-30 17:44:07 -0700880String8 CameraService::toString(std::set<userid_t> intSet) {
881 String8 s("");
882 bool first = true;
883 for (userid_t i : intSet) {
884 if (first) {
885 s.appendFormat("%d", i);
886 first = false;
887 } else {
888 s.appendFormat(", %d", i);
889 }
890 }
891 return s;
892}
893
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800894int32_t CameraService::mapToInterface(TorchModeStatus status) {
895 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
896 switch (status) {
897 case TorchModeStatus::NOT_AVAILABLE:
898 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
899 break;
900 case TorchModeStatus::AVAILABLE_OFF:
901 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
902 break;
903 case TorchModeStatus::AVAILABLE_ON:
904 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
905 break;
906 default:
907 ALOGW("Unknown new flash status: %d", status);
908 }
909 return serviceStatus;
910}
911
912CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
913 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
914 switch (status) {
915 case CameraDeviceStatus::NOT_PRESENT:
916 serviceStatus = StatusInternal::NOT_PRESENT;
917 break;
918 case CameraDeviceStatus::PRESENT:
919 serviceStatus = StatusInternal::PRESENT;
920 break;
921 case CameraDeviceStatus::ENUMERATING:
922 serviceStatus = StatusInternal::ENUMERATING;
923 break;
924 default:
925 ALOGW("Unknown new HAL device status: %d", status);
926 }
927 return serviceStatus;
928}
929
930int32_t CameraService::mapToInterface(StatusInternal status) {
931 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
932 switch (status) {
933 case StatusInternal::NOT_PRESENT:
934 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
935 break;
936 case StatusInternal::PRESENT:
937 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
938 break;
939 case StatusInternal::ENUMERATING:
940 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
941 break;
942 case StatusInternal::NOT_AVAILABLE:
943 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
944 break;
945 case StatusInternal::UNKNOWN:
946 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
947 break;
948 default:
949 ALOGW("Unknown new internal device status: %d", status);
950 }
951 return serviceStatus;
952}
953
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800954Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -0700955 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700956
Chien-Yu Chen98a668f2015-12-18 14:10:33 -0800957 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -0800958 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800960 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800961 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800962 sp<ICameraClient>{nullptr}, id, cameraId,
963 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +0900964 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -0700965 API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800966 ).isOk()) {
967 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -0700968 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -0700970}
971
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800972Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -0700973 /*out*/
974 CameraParameters* parameters) {
975
976 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
977
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800978 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -0700979
980 if (parameters == NULL) {
981 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800982 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -0700983 }
984
Ruben Brunkcc776712015-02-17 20:18:47 -0800985 String8 id = String8::format("%d", cameraId);
986
987 // Check if we already have parameters
988 {
989 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -0700990 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -0800991 auto cameraState = getCameraState(id);
992 if (cameraState == nullptr) {
993 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800994 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
995 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -0800996 }
997 CameraParameters p = cameraState->getShimParams();
998 if (!p.isEmpty()) {
999 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001000 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001001 }
1002 }
1003
Jayant Chowdhary12361932018-08-27 14:46:13 -07001004 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001005 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001006 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001007 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001008 // Error already logged by callee
1009 return ret;
1010 }
1011
1012 // Check for parameters again
1013 {
1014 // Scope for service lock
1015 Mutex::Autolock lock(mServiceLock);
1016 auto cameraState = getCameraState(id);
1017 if (cameraState == nullptr) {
1018 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001019 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1020 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001021 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001022 CameraParameters p = cameraState->getShimParams();
1023 if (!p.isEmpty()) {
1024 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001025 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001026 }
1027 }
1028
Ruben Brunkcc776712015-02-17 20:18:47 -08001029 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1030 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001031 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001032}
1033
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001034// Can camera service trust the caller based on the calling UID?
1035static bool isTrustedCallingUid(uid_t uid) {
1036 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001037 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001038 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001039 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001040 return true;
1041 default:
1042 return false;
1043 }
1044}
1045
Nicholas Sauera3620332019-04-03 14:05:17 -07001046static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1047 PermissionController pc;
1048 uid = pc.getPackageUid(packageName, 0);
1049 if (uid <= 0) {
1050 ALOGE("Unknown package: '%s'", String8(packageName).string());
1051 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1052 return BAD_VALUE;
1053 }
1054
1055 if (userId < 0) {
1056 ALOGE("Invalid user: %d", userId);
1057 dprintf(err, "Invalid user: %d\n", userId);
1058 return BAD_VALUE;
1059 }
1060
1061 uid = multiuser_get_uid(userId, uid);
1062 return NO_ERROR;
1063}
1064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001066 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1067 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001068
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001069#ifdef __BRILLO__
1070 UNUSED(clientName8);
1071 UNUSED(clientUid);
1072 UNUSED(clientPid);
1073 UNUSED(originalClientPid);
1074#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001075 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1076 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001077 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001078 return allowed;
1079 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001080#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001081
Jayant Chowdhary12361932018-08-27 14:46:13 -07001082 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001083
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001084 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001085 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1086 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001087 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1088 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001089 }
1090
Ruben Brunkcc776712015-02-17 20:18:47 -08001091 if (getCameraState(cameraId) == nullptr) {
1092 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1093 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001094 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1095 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 }
1097
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001098 status_t err = checkIfDeviceIsUsable(cameraId);
1099 if (err != NO_ERROR) {
1100 switch(err) {
1101 case -ENODEV:
1102 case -EBUSY:
1103 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1104 "No camera device with ID \"%s\" currently available", cameraId.string());
1105 default:
1106 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1107 "Unknown error connecting to ID \"%s\"", cameraId.string());
1108 }
1109 }
1110 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001111}
1112
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001113Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001114 const String8& clientName8, int& clientUid, int& clientPid,
1115 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001116 int callingPid = CameraThreadState::getCallingPid();
1117 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001119 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001121 clientUid = callingUid;
1122 } else if (!isTrustedCallingUid(callingUid)) {
1123 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1124 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001125 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1126 "Untrusted caller (calling PID %d, UID %d) trying to "
1127 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1128 callingPid, callingUid, cameraId.string(),
1129 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 }
1131
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001132 // Check if we can trust clientPid
1133 if (clientPid == USE_CALLING_PID) {
1134 clientPid = callingPid;
1135 } else if (!isTrustedCallingUid(callingUid)) {
1136 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1137 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001138 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1139 "Untrusted caller (calling PID %d, UID %d) trying to "
1140 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1141 callingPid, callingUid, cameraId.string(),
1142 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001143 }
1144
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001145 if (shouldRejectSystemCameraConnection(cameraId)) {
1146 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1147 cameraId.c_str());
1148 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1149 "available", cameraId.string());
1150 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001151 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1152 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1153 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1154 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1155 "found while trying to query device kind", cameraId.string());
1156
1157 }
1158
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001159 // If it's not calling from cameraserver, check the permission if the
1160 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1161 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001162 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001163 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001164 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001165 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001166 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1167 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1168 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001169 }
1170
Svet Ganova453d0d2018-01-11 15:37:58 -08001171 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001172 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001173 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001174 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1175 clientPid, clientUid);
1176 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001177 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1178 "calling UID %d proc state %" PRId32 ")",
1179 clientName8.string(), clientUid, clientPid, cameraId.string(),
1180 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001181 }
1182
Michael Grooverd1d435a2018-12-18 17:39:42 -08001183 // If sensor privacy is enabled then prevent access to the camera
1184 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1185 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1186 return STATUS_ERROR_FMT(ERROR_DISABLED,
1187 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1188 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1189 }
1190
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001191 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1192 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001193 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001194 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195
Ruben Brunk6267b532015-04-30 17:44:07 -07001196 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001197
Ruben Brunka8ca9152015-04-07 14:23:40 -07001198 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001199 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001200 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001201 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001202 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1203 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1204 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001205 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1206 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1207 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001208 }
1209
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001210 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001211}
1212
1213status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1214 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001215 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001216 if (cameraState == nullptr) {
1217 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1218 cameraId.string());
1219 return -ENODEV;
1220 }
1221
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001222 StatusInternal currentStatus = cameraState->getStatus();
1223 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001224 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1225 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001226 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001227 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001228 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1229 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001230 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001231 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001232
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001234}
1235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1237 const CameraService::DescriptorPtr& desc) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001238
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 // Make a descriptor for the incoming client
1240 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1241 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1242
1243 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1244 String8(client->getPackageName()));
1245
1246 if (evicted.size() > 0) {
1247 // This should never happen - clients should already have been removed in disconnect
1248 for (auto& i : evicted) {
1249 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1250 __FUNCTION__, i->getKey().string());
1251 }
1252
1253 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1254 __FUNCTION__);
1255 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001256
1257 // And register a death notification for the client callback. Do
1258 // this last to avoid Binder policy where a nested Binder
1259 // transaction might be pre-empted to service the client death
1260 // notification if the client process dies before linkToDeath is
1261 // invoked.
1262 sp<IBinder> remoteCallback = client->getRemote();
1263 if (remoteCallback != nullptr) {
1264 remoteCallback->linkToDeath(this);
1265 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001266}
1267
1268status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1269 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1270 /*out*/
1271 sp<BasicClient>* client,
1272 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001273 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001275 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001276 DescriptorPtr clientDescriptor;
1277 {
1278 if (effectiveApiLevel == API_1) {
1279 // If we are using API1, any existing client for this camera ID with the same remote
1280 // should be returned rather than evicted to allow MediaRecorder to work properly.
1281
1282 auto current = mActiveClientManager.get(cameraId);
1283 if (current != nullptr) {
1284 auto clientSp = current->getValue();
1285 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001286 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1287 ALOGW("CameraService connect called from same client, but with a different"
1288 " API level, evicting prior client...");
1289 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001291 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001292 *client = clientSp;
1293 return NO_ERROR;
1294 }
1295 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001296 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001297 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001298
Ruben Brunkcc776712015-02-17 20:18:47 -08001299 // Get current active client PIDs
1300 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1301 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001302
Emilian Peev8131a262017-02-01 12:33:43 +00001303 std::vector<int> priorityScores(ownerPids.size());
1304 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001305
Emilian Peev8131a262017-02-01 12:33:43 +00001306 // Get priority scores of all active PIDs
1307 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1308 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1309 /*out*/&priorityScores[0]);
1310 if (err != OK) {
1311 ALOGE("%s: Priority score query failed: %d",
1312 __FUNCTION__, err);
1313 return err;
1314 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001315
Ruben Brunkcc776712015-02-17 20:18:47 -08001316 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001317 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001318 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001319 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001320 resource_policy::ClientPriority(priorityScores[i], states[i],
1321 /* isVendorClient won't get copied over*/ false));
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 }
1323 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001324
Ruben Brunkcc776712015-02-17 20:18:47 -08001325 // Get state for the given cameraId
1326 auto state = getCameraState(cameraId);
1327 if (state == nullptr) {
1328 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1329 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001330 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001331 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001332 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001333
1334 // Make descriptor for incoming client
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001335 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1337 state->getConflicting(),
Emilian Peev8131a262017-02-01 12:33:43 +00001338 priorityScores[priorityScores.size() - 1],
1339 clientPid,
1340 states[states.size() - 1]);
Ruben Brunkcc776712015-02-17 20:18:47 -08001341
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001342 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1343
Ruben Brunkcc776712015-02-17 20:18:47 -08001344 // Find clients that would be evicted
1345 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1346
1347 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1348 // background, so we cannot do evictions
1349 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1350 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1351 " priority).", clientPid);
1352
1353 sp<BasicClient> clientSp = clientDescriptor->getValue();
1354 String8 curTime = getFormattedCurrentTime();
1355 auto incompatibleClients =
1356 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1357
1358 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001359 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001361 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001362
1363 for (auto& i : incompatibleClients) {
1364 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001365 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1366 i->getKey().string(),
1367 String8{i->getValue()->getPackageName()}.string(),
1368 i->getOwnerId(), i->getPriority().getScore(),
1369 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001370 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001371 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001372 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001373 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 }
1375
1376 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001377 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 mEventLog.add(msg);
1379
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001380 auto current = mActiveClientManager.get(cameraId);
1381 if (current != nullptr) {
1382 return -EBUSY; // CAMERA_IN_USE
1383 } else {
1384 return -EUSERS; // MAX_CAMERAS_IN_USE
1385 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 }
1387
1388 for (auto& i : evicted) {
1389 sp<BasicClient> clientSp = i->getValue();
1390 if (clientSp.get() == nullptr) {
1391 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1392
1393 // TODO: Remove this
1394 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1395 __FUNCTION__);
1396 mActiveClientManager.remove(i);
1397 continue;
1398 }
1399
1400 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1401 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001402 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001403
Ruben Brunkcc776712015-02-17 20:18:47 -08001404 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001405 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001406 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1407 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001409 i->getOwnerId(), i->getPriority().getScore(),
1410 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001411 packageName.string(), clientPid, clientPriority.getScore(),
1412 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001413
1414 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001415 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001416 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001417 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001418 }
1419
Ruben Brunkcc776712015-02-17 20:18:47 -08001420 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1421 // other clients from connecting in mServiceLockWrapper if held
1422 mServiceLock.unlock();
1423
1424 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001425 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001426
1427 // Destroy evicted clients
1428 for (auto& i : evictedClients) {
1429 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001430 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001431 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001432
Jayant Chowdhary12361932018-08-27 14:46:13 -07001433 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001434
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001435 for (const auto& i : evictedClients) {
1436 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1437 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1438 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1439 if (ret == TIMED_OUT) {
1440 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1441 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1442 mActiveClientManager.toString().string());
1443 return -EBUSY;
1444 }
1445 if (ret != NO_ERROR) {
1446 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1447 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1448 ret, mActiveClientManager.toString().string());
1449 return ret;
1450 }
1451 }
1452
1453 evictedClients.clear();
1454
Ruben Brunkcc776712015-02-17 20:18:47 -08001455 // Once clients have been disconnected, relock
1456 mServiceLock.lock();
1457
1458 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1459 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1460 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001461 }
1462
Ruben Brunkcc776712015-02-17 20:18:47 -08001463 *partial = clientDescriptor;
1464 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001465}
1466
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001468 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001469 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001470 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001471 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001472 int clientPid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001473 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001474 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001475
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001476 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001477 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001478
1479 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001480 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001481 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001482 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, {},
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001483 clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001484
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001485 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001486 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001487 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001488 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 }
1490
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001491 *device = client;
1492 return ret;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493}
1494
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001495Status CameraService::connectLegacy(
Zhijun Heb10cdad2014-06-16 16:38:35 -07001496 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001497 int api1CameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001498 const String16& clientPackageName,
Zhijun Heb10cdad2014-06-16 16:38:35 -07001499 int clientUid,
1500 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001501 sp<ICamera>* device) {
Zhijun Heb10cdad2014-06-16 16:38:35 -07001502
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001503 ATRACE_CALL();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001504 String8 id = cameraIdIntToStr(api1CameraId);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001505
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001506 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001507 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001508 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001509 clientPackageName, {}, clientUid, USE_CALLING_PID, API_1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001510 /*shimUpdateOnly*/ false, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001511
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001512 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001513 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001514 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001515 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001516 }
1517
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001518 *device = client;
1519 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001520}
1521
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001522bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1523 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001524 // If the client is not a vendor client, don't add listener if
1525 // a) the camera is a publicly hidden secure camera OR
1526 // b) the camera is a system only camera and the client doesn't
1527 // have android.permission.SYSTEM_CAMERA permissions.
1528 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1529 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1530 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001531 return true;
1532 }
1533 return false;
1534}
1535
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001536bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1537 // Rules for rejection:
1538 // 1) If cameraserver tries to access this camera device, accept the
1539 // connection.
1540 // 2) The camera device is a publicly hidden secure camera device AND some
1541 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1542 // reject it.
1543 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1544 // and the serving thread is a non hwbinder thread, the client must have
1545 // android.permission.SYSTEM_CAMERA permissions to connect.
1546
1547 int cPid = CameraThreadState::getCallingPid();
1548 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001549 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1550 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
1551 ALOGE("%s: Invalid camera id %s, ", __FUNCTION__, cameraId.c_str());
1552 return true;
1553 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001554
1555 // (1) Cameraserver trying to connect, accept.
1556 if (CameraThreadState::getCallingPid() == getpid()) {
1557 return false;
1558 }
1559 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001560 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001561 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1562 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1563 return true;
1564 }
1565 // (3) Here we only check for permissions if it is a system only camera device. This is since
1566 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1567 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1568 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001569 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001570 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1571 !hasPermissionsForSystemCamera(cPid, cUid)) {
1572 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1573 cameraId.c_str());
1574 return true;
1575 }
1576
1577 return false;
1578}
1579
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001580Status CameraService::connectDevice(
1581 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001582 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001583 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001584 const std::optional<String16>& clientFeatureId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001585 int clientUid,
1586 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001587 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001588
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001589 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001590 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001591 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001592 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001593 String16 clientPackageNameAdj = clientPackageName;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001594
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001595 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001596 std::string vendorClient =
1597 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1598 clientPackageNameAdj = String16(vendorClient.c_str());
1599 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001600 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001601 /*api1CameraId*/-1,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001602 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj, clientFeatureId,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001603 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001604
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001605 if(!ret.isOk()) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001606 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001607 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001608 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001609 }
1610
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001611 *device = client;
1612 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001613}
1614
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001615template<class CALLBACK, class CLIENT>
1616Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001617 int api1CameraId, int halVersion, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001618 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001619 apiLevel effectiveApiLevel, bool shimUpdateOnly,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001620 /*out*/sp<CLIENT>& device) {
1621 binder::Status ret = binder::Status::ok();
1622
1623 String8 clientName8(clientPackageName);
1624
1625 int originalClientPid = 0;
1626
1627 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1628 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1629 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1630 static_cast<int>(effectiveApiLevel));
1631
1632 sp<CLIENT> client = nullptr;
1633 {
1634 // Acquire mServiceLock and prevent other clients from connecting
1635 std::unique_ptr<AutoConditionLock> lock =
1636 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1637
1638 if (lock == nullptr) {
1639 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1640 , clientPid);
1641 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1642 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1643 cameraId.string(), clientName8.string(), clientPid);
1644 }
1645
1646 // Enforce client permissions and do basic sanity checks
1647 if(!(ret = validateConnectLocked(cameraId, clientName8,
1648 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1649 return ret;
1650 }
1651
1652 // Check the shim parameters after acquiring lock, if they have already been updated and
1653 // we were doing a shim update, return immediately
1654 if (shimUpdateOnly) {
1655 auto cameraState = getCameraState(cameraId);
1656 if (cameraState != nullptr) {
1657 if (!cameraState->getShimParams().isEmpty()) return ret;
1658 }
1659 }
1660
1661 status_t err;
1662
1663 sp<BasicClient> clientTmp = nullptr;
1664 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1665 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1666 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1667 /*out*/&partial)) != NO_ERROR) {
1668 switch (err) {
1669 case -ENODEV:
1670 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1671 "No camera device with ID \"%s\" currently available",
1672 cameraId.string());
1673 case -EBUSY:
1674 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1675 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1676 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001677 case -EUSERS:
1678 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1679 "Too many cameras already open, cannot open camera \"%s\"",
1680 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001681 default:
1682 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1683 "Unexpected error %s (%d) opening camera \"%s\"",
1684 strerror(-err), err, cameraId.string());
1685 }
1686 }
1687
1688 if (clientTmp.get() != nullptr) {
1689 // Handle special case for API1 MediaRecorder where the existing client is returned
1690 device = static_cast<CLIENT*>(clientTmp.get());
1691 return ret;
1692 }
1693
1694 // give flashlight a chance to close devices if necessary.
1695 mFlashlight->prepareDeviceOpen(cameraId);
1696
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001697 int facing = -1;
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001698 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001699 if (facing == -1) {
1700 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1701 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1702 "Unable to get camera device \"%s\" facing", cameraId.string());
1703 }
1704
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001705 sp<BasicClient> tmp = nullptr;
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001706 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001707 cameraId, api1CameraId, facing,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001708 clientPid, clientUid, getpid(),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001709 halVersion, deviceVersion, effectiveApiLevel,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001710 /*out*/&tmp)).isOk()) {
1711 return ret;
1712 }
1713 client = static_cast<CLIENT*>(tmp.get());
1714
1715 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1716 __FUNCTION__);
1717
Emilian Peevbd8c5032018-02-14 23:05:40 +00001718 err = client->initialize(mCameraProviderManager, mMonitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001719 if (err != OK) {
1720 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001721 // Errors could be from the HAL module open call or from AppOpsManager
1722 switch(err) {
1723 case BAD_VALUE:
1724 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1725 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1726 case -EBUSY:
1727 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1728 "Camera \"%s\" is already open", cameraId.string());
1729 case -EUSERS:
1730 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1731 "Too many cameras already open, cannot open camera \"%s\"",
1732 cameraId.string());
1733 case PERMISSION_DENIED:
1734 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1735 "No permission to open camera \"%s\"", cameraId.string());
1736 case -EACCES:
1737 return STATUS_ERROR_FMT(ERROR_DISABLED,
1738 "Camera \"%s\" disabled by policy", cameraId.string());
1739 case -ENODEV:
1740 default:
1741 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1742 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1743 strerror(-err), err);
1744 }
1745 }
1746
1747 // Update shim paremeters for legacy clients
1748 if (effectiveApiLevel == API_1) {
1749 // Assume we have always received a Client subclass for API1
1750 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1751 String8 rawParams = shimClient->getParameters();
1752 CameraParameters params(rawParams);
1753
1754 auto cameraState = getCameraState(cameraId);
1755 if (cameraState != nullptr) {
1756 cameraState->setShimParams(params);
1757 } else {
1758 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1759 __FUNCTION__, cameraId.string());
1760 }
1761 }
1762
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001763 // Set rotate-and-crop override behavior
1764 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1765 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
1766 }
1767
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001768 if (shimUpdateOnly) {
1769 // If only updating legacy shim parameters, immediately disconnect client
1770 mServiceLock.unlock();
1771 client->disconnect();
1772 mServiceLock.lock();
1773 } else {
1774 // Otherwise, add client to active clients list
1775 finishConnectLocked(client, partial);
1776 }
1777 } // lock is destroyed, allow further connect calls
1778
1779 // Important: release the mutex here so the client can call back into the service from its
1780 // destructor (can be at the end of the call)
1781 device = client;
1782 return ret;
1783}
1784
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001785status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1786 if (offlineClient.get() == nullptr) {
1787 return BAD_VALUE;
1788 }
1789
1790 {
1791 // Acquire mServiceLock and prevent other clients from connecting
1792 std::unique_ptr<AutoConditionLock> lock =
1793 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1794
1795 if (lock == nullptr) {
1796 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1797 , __FUNCTION__, offlineClient->getClientPid());
1798 return TIMED_OUT;
1799 }
1800
1801 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1802 if (onlineClientDesc.get() == nullptr) {
1803 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1804 cameraId.c_str());
1805 return BAD_VALUE;
1806 }
1807
1808 // Offline clients do not evict or conflict with other online devices. Resource sharing
1809 // conflicts are handled by the camera provider which will either succeed or fail before
1810 // reaching this method.
1811 const auto& onlinePriority = onlineClientDesc->getPriority();
1812 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1813 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1814 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
1815 onlineClientDesc->getOwnerId(), onlinePriority.getState());
1816
1817 // Allow only one offline device per camera
1818 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1819 if (!incompatibleClients.empty()) {
1820 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1821 return BAD_VALUE;
1822 }
1823
1824 auto err = offlineClient->initialize(mCameraProviderManager, mMonitorTags);
1825 if (err != OK) {
1826 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1827 return err;
1828 }
1829
1830 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1831 if (evicted.size() > 0) {
1832 for (auto& i : evicted) {
1833 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1834 __FUNCTION__, i->getKey().string());
1835 }
1836
1837 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1838 "properly", __FUNCTION__);
1839
1840 return BAD_VALUE;
1841 }
1842
1843 logConnectedOffline(offlineClientDesc->getKey(),
1844 static_cast<int>(offlineClientDesc->getOwnerId()),
1845 String8(offlineClient->getPackageName()));
1846
1847 sp<IBinder> remoteCallback = offlineClient->getRemote();
1848 if (remoteCallback != nullptr) {
1849 remoteCallback->linkToDeath(this);
1850 }
1851 } // lock is destroyed, allow further connect calls
1852
1853 return OK;
1854}
1855
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001856Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001857 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001858 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001859
1860 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07001861 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001862 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001863 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1864 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001865 }
1866
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001867 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07001868 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001869
1870 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08001871 auto state = getCameraState(id);
1872 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07001873 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001874 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1875 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 }
1877
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001878 StatusInternal cameraStatus = state->getStatus();
1879 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001880 cameraStatus != StatusInternal::NOT_AVAILABLE) {
1881 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001882 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1883 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001884 }
1885
1886 {
1887 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001888 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001889 status_t err = getTorchStatusLocked(id, &status);
1890 if (err != OK) {
1891 if (err == NAME_NOT_FOUND) {
1892 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1893 "Camera \"%s\" does not have a flash unit", id.string());
1894 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001895 ALOGE("%s: getting current torch status failed for camera %s",
1896 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001897 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1898 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1899 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001900 }
1901
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001902 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001903 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001904 ALOGE("%s: torch mode of camera %s is not available because "
1905 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001906 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1907 "Torch for camera \"%s\" is not available due to an existing camera user",
1908 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001909 } else {
1910 ALOGE("%s: torch mode of camera %s is not available due to "
1911 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001912 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1913 "Torch for camera \"%s\" is not available due to insufficient resources",
1914 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001915 }
1916 }
1917 }
1918
Ruben Brunk99e69712015-05-26 17:25:07 -07001919 {
1920 // Update UID map - this is used in the torch status changed callbacks, so must be done
1921 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07001922 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07001923 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1924 mTorchUidMap[id].first = uid;
1925 mTorchUidMap[id].second = uid;
1926 } else {
1927 // Set the pending UID
1928 mTorchUidMap[id].first = uid;
1929 }
1930 }
1931
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001932 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07001933
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001934 if (err != OK) {
1935 int32_t errorCode;
1936 String8 msg;
1937 switch (err) {
1938 case -ENOSYS:
1939 msg = String8::format("Camera \"%s\" has no flashlight",
1940 id.string());
1941 errorCode = ERROR_ILLEGAL_ARGUMENT;
1942 break;
1943 default:
1944 msg = String8::format(
1945 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1946 id.string(), enabled, strerror(-err), err);
1947 errorCode = ERROR_INVALID_OPERATION;
1948 }
1949 ALOGE("%s: %s", __FUNCTION__, msg.string());
1950 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001951 }
1952
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001953 {
1954 // update the link to client's death
1955 Mutex::Autolock al(mTorchClientMapMutex);
1956 ssize_t index = mTorchClientMap.indexOfKey(id);
1957 if (enabled) {
1958 if (index == NAME_NOT_FOUND) {
1959 mTorchClientMap.add(id, clientBinder);
1960 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07001961 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001962 mTorchClientMap.replaceValueAt(index, clientBinder);
1963 }
1964 clientBinder->linkToDeath(this);
1965 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07001966 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001967 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001968 }
1969
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07001970 int clientPid = CameraThreadState::getCallingPid();
1971 const char *id_cstr = id.c_str();
1972 const char *torchState = enabled ? "on" : "off";
1973 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1974 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001975 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001976}
1977
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001978Status CameraService::notifySystemEvent(int32_t eventId,
1979 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001980 const int pid = CameraThreadState::getCallingPid();
1981 const int selfPid = getpid();
1982
1983 // Permission checks
1984 if (pid != selfPid) {
1985 // Ensure we're being called by system_server, or similar process with
1986 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001987 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001988 const int uid = CameraThreadState::getCallingUid();
1989 ALOGE("Permission Denial: cannot send updates to camera service about system"
1990 " events from pid=%d, uid=%d", pid, uid);
1991 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09001992 "No permission to send updates to camera service about system events"
1993 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09001994 }
1995 }
1996
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001997 ATRACE_CALL();
1998
Ruben Brunk36597b22015-03-20 22:15:57 -07001999 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002000 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002001 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002002 // from a system server crash
2003 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002004 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002005 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002006 break;
2007 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002008 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002009 default: {
2010 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2011 eventId);
2012 break;
2013 }
2014 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002015 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002016}
2017
Emilian Peev53722fa2019-02-22 17:47:20 -08002018void CameraService::notifyMonitoredUids() {
2019 Mutex::Autolock lock(mStatusListenerLock);
2020
2021 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002022 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002023 if (!ret.isOk()) {
2024 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2025 ret.exceptionCode());
2026 }
2027 }
2028}
2029
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002030Status CameraService::notifyDeviceStateChange(int64_t newState) {
2031 const int pid = CameraThreadState::getCallingPid();
2032 const int selfPid = getpid();
2033
2034 // Permission checks
2035 if (pid != selfPid) {
2036 // Ensure we're being called by system_server, or similar process with
2037 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002038 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002039 const int uid = CameraThreadState::getCallingUid();
2040 ALOGE("Permission Denial: cannot send updates to camera service about device"
2041 " state changes from pid=%d, uid=%d", pid, uid);
2042 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2043 "No permission to send updates to camera service about device state"
2044 " changes from pid=%d, uid=%d", pid, uid);
2045 }
2046 }
2047
2048 ATRACE_CALL();
2049
2050 using hardware::camera::provider::V2_5::DeviceState;
2051 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2052 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2053 newDeviceState |= DeviceState::BACK_COVERED;
2054 }
2055 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2056 newDeviceState |= DeviceState::FRONT_COVERED;
2057 }
2058 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2059 newDeviceState |= DeviceState::FOLDED;
2060 }
2061 // Only map vendor bits directly
2062 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2063 newDeviceState |= vendorBits;
2064
2065 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
2066 Mutex::Autolock l(mServiceLock);
2067 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2068
2069 return Status::ok();
2070}
2071
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002072 Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002073 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2074 ATRACE_CALL();
2075 if (!concurrentCameraIds) {
2076 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2077 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2078 }
2079
2080 if (!mInitialized) {
2081 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2082 return STATUS_ERROR(ERROR_DISCONNECTED,
2083 "Camera subsystem is not available");
2084 }
2085 // First call into the provider and get the set of concurrent camera
2086 // combinations
2087 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002088 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002089 for (auto &combination : concurrentCameraCombinations) {
2090 std::vector<std::string> validCombination;
2091 for (auto &cameraId : combination) {
2092 // if the camera state is not present, skip
2093 String8 cameraIdStr(cameraId.c_str());
2094 auto state = getCameraState(cameraIdStr);
2095 if (state == nullptr) {
2096 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2097 continue;
2098 }
2099 StatusInternal status = state->getStatus();
2100 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2101 continue;
2102 }
2103 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2104 continue;
2105 }
2106 validCombination.push_back(cameraId);
2107 }
2108 if (validCombination.size() != 0) {
2109 concurrentCameraIds->push_back(std::move(validCombination));
2110 }
2111 }
2112 return Status::ok();
2113}
2114
2115Status CameraService::isConcurrentSessionConfigurationSupported(
2116 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
2117 /*out*/bool* isSupported) {
2118 if (!isSupported) {
2119 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2120 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2121 }
2122
2123 if (!mInitialized) {
2124 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2125 return STATUS_ERROR(ERROR_DISCONNECTED,
2126 "Camera subsystem is not available");
2127 }
2128
2129 // Check for camera permissions
2130 int callingPid = CameraThreadState::getCallingPid();
2131 int callingUid = CameraThreadState::getCallingUid();
2132 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2133 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2134 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2135 "android.permission.CAMERA needed to call"
2136 "isConcurrentSessionConfigurationSupported");
2137 }
2138
2139 status_t res =
2140 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
2141 cameraIdsAndSessionConfigurations, isSupported);
2142 if (res != OK) {
2143 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2144 "support %s (%d)", strerror(-res), res);
2145 }
2146 return Status::ok();
2147}
2148
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002149Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2150 /*out*/
2151 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002152 return addListenerHelper(listener, cameraStatuses);
2153}
2154
2155Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2156 /*out*/
2157 std::vector<hardware::CameraStatus> *cameraStatuses,
2158 bool isVendorListener) {
2159
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002160 ATRACE_CALL();
2161
Igor Murashkinbfc99152013-02-27 12:55:20 -08002162 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002163
Ruben Brunk3450ba72015-06-16 11:00:37 -07002164 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002165 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002166 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002167 }
2168
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002169 auto clientUid = CameraThreadState::getCallingUid();
2170 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002171 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
2172 clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002173
Igor Murashkinbfc99152013-02-27 12:55:20 -08002174 Mutex::Autolock lock(mServiceLock);
2175
Ruben Brunkcc776712015-02-17 20:18:47 -08002176 {
2177 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002178 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002179 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 ALOGW("%s: Tried to add listener %p which was already subscribed",
2181 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002182 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002183 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002184 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002185
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002186 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002187 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2188 openCloseCallbackAllowed);
Emilian Peev53722fa2019-02-22 17:47:20 -08002189 auto ret = serviceListener->initialize();
2190 if (ret != NO_ERROR) {
2191 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2192 strerror(-ret), ret);
2193 ALOGE("%s: %s", __FUNCTION__, msg.string());
2194 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2195 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002196 // The listener still needs to be added to the list of listeners, regardless of what
2197 // permissions the listener process has / whether it is a vendor listener. Since it might be
2198 // eligible to listen to other camera ids.
2199 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002200 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002201 }
2202
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002203 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002204 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002205 Mutex::Autolock lock(mCameraStatesLock);
2206 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002207 cameraStatuses->emplace_back(i.first,
2208 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds());
Igor Murashkincba2c162013-03-20 15:56:31 -07002209 }
2210 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002211 // Remove the camera statuses that should be hidden from the client, we do
2212 // this after collecting the states in order to avoid holding
2213 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2214 // the same time.
2215 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2216 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2217 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2218 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2219 ALOGE("%s: Invalid camera id %s, skipping status update",
2220 __FUNCTION__, s.cameraId.c_str());
2221 return true;
2222 }
2223 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2224 clientUid);}), cameraStatuses->end());
2225
Igor Murashkincba2c162013-03-20 15:56:31 -07002226
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002227 /*
2228 * Immediately signal current torch status to this listener only
2229 * This may be a subset of all the devices, so don't include it in the response directly
2230 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002231 {
2232 Mutex::Autolock al(mTorchStatusMutex);
2233 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002234 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002235 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002236 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002237 }
2238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002240}
Ruben Brunkcc776712015-02-17 20:18:47 -08002241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002242Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002243 ATRACE_CALL();
2244
Igor Murashkinbfc99152013-02-27 12:55:20 -08002245 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2246
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002247 if (listener == 0) {
2248 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002250 }
2251
Igor Murashkinbfc99152013-02-27 12:55:20 -08002252 Mutex::Autolock lock(mServiceLock);
2253
Ruben Brunkcc776712015-02-17 20:18:47 -08002254 {
2255 Mutex::Autolock lock(mStatusListenerLock);
2256 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002257 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2258 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2259 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002260 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002261 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002262 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002263 }
2264 }
2265
2266 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2267 __FUNCTION__, listener.get());
2268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002269 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002270}
2271
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002272Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002273
2274 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002275 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2276
2277 if (parameters == NULL) {
2278 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002280 }
2281
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002282 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002283
2284 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002285 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002286 // Error logged by caller
2287 return ret;
2288 }
2289
2290 String8 shimParamsString8 = shimParams.flatten();
2291 String16 shimParamsString16 = String16(shimParamsString8);
2292
2293 *parameters = shimParamsString16;
2294
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002295 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002296}
2297
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002298Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2299 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002300 ATRACE_CALL();
2301
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002302 const String8 id = String8(cameraId);
2303
2304 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002305
2306 switch (apiVersion) {
2307 case API_VERSION_1:
2308 case API_VERSION_2:
2309 break;
2310 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002311 String8 msg = String8::format("Unknown API version %d", apiVersion);
2312 ALOGE("%s: %s", __FUNCTION__, msg.string());
2313 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002314 }
2315
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002316 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002317 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002318 case CAMERA_DEVICE_API_VERSION_1_0:
2319 case CAMERA_DEVICE_API_VERSION_3_0:
2320 case CAMERA_DEVICE_API_VERSION_3_1:
2321 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002322 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2323 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 *isSupported = false;
2325 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002326 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2327 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002328 *isSupported = true;
2329 }
2330 break;
2331 case CAMERA_DEVICE_API_VERSION_3_2:
2332 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002333 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002334 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002335 case CAMERA_DEVICE_API_VERSION_3_6:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002336 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2337 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002338 *isSupported = true;
2339 break;
2340 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002341 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 ALOGE("%s: %s", __FUNCTION__, msg.string());
2343 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002344 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002345 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002346 String8 msg = String8::format("Unknown device version %x for device %s",
2347 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002348 ALOGE("%s: %s", __FUNCTION__, msg.string());
2349 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2350 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002351 }
2352
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002353 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002354}
2355
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002356Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2357 /*out*/ bool *isSupported) {
2358 ATRACE_CALL();
2359
2360 const String8 id = String8(cameraId);
2361
2362 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2363 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2364
2365 return Status::ok();
2366}
2367
Ruben Brunkcc776712015-02-17 20:18:47 -08002368void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002369 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002370 for (auto& i : mActiveClientManager.getAll()) {
2371 auto clientSp = i->getValue();
2372 if (clientSp.get() == client) {
2373 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002374 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002375 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002376 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002377}
2378
Ruben Brunkcc776712015-02-17 20:18:47 -08002379bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002380 bool ret = false;
2381 {
2382 // Acquire mServiceLock and prevent other clients from connecting
2383 std::unique_ptr<AutoConditionLock> lock =
2384 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002385
Igor Murashkin634a5152013-02-20 17:15:11 -08002386
Ruben Brunkcc776712015-02-17 20:18:47 -08002387 std::vector<sp<BasicClient>> evicted;
2388 for (auto& i : mActiveClientManager.getAll()) {
2389 auto clientSp = i->getValue();
2390 if (clientSp.get() == nullptr) {
2391 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2392 mActiveClientManager.remove(i);
2393 continue;
2394 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002395 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002396 mActiveClientManager.remove(i);
2397 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002398
Ruben Brunkcc776712015-02-17 20:18:47 -08002399 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002400 clientSp->notifyError(
2401 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002402 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002403 }
2404 }
2405
Ruben Brunkcc776712015-02-17 20:18:47 -08002406 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2407 // other clients from connecting in mServiceLockWrapper if held
2408 mServiceLock.unlock();
2409
Ruben Brunk36597b22015-03-20 22:15:57 -07002410 // Do not clear caller identity, remote caller should be client proccess
2411
Ruben Brunkcc776712015-02-17 20:18:47 -08002412 for (auto& i : evicted) {
2413 if (i.get() != nullptr) {
2414 i->disconnect();
2415 ret = true;
2416 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002417 }
2418
Ruben Brunkcc776712015-02-17 20:18:47 -08002419 // Reacquire mServiceLock
2420 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002421
Ruben Brunkcc776712015-02-17 20:18:47 -08002422 } // lock is destroyed, allow further connect calls
2423
2424 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002425}
2426
Ruben Brunkcc776712015-02-17 20:18:47 -08002427std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2428 const String8& cameraId) const {
2429 std::shared_ptr<CameraState> state;
2430 {
2431 Mutex::Autolock lock(mCameraStatesLock);
2432 auto iter = mCameraStates.find(cameraId);
2433 if (iter != mCameraStates.end()) {
2434 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
2436 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002437 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438}
2439
Ruben Brunkcc776712015-02-17 20:18:47 -08002440sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2441 // Remove from active clients list
2442 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2443 if (clientDescriptorPtr == nullptr) {
2444 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2445 cameraId.string());
2446 return sp<BasicClient>{nullptr};
2447 }
2448
2449 return clientDescriptorPtr->getValue();
Keun young Parkd8973a72012-03-28 14:13:09 -07002450}
2451
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002452void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002453 // Acquire mServiceLock and prevent other clients from connecting
2454 std::unique_ptr<AutoConditionLock> lock =
2455 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2456
Ruben Brunk6267b532015-04-30 17:44:07 -07002457 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 for (size_t i = 0; i < newUserIds.size(); i++) {
2459 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002460 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002462 return;
2463 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002464 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002465 }
2466
Ruben Brunka8ca9152015-04-07 14:23:40 -07002467
Ruben Brunk6267b532015-04-30 17:44:07 -07002468 if (newAllowedUsers == mAllowedUsers) {
2469 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2470 return;
2471 }
2472
2473 logUserSwitch(mAllowedUsers, newAllowedUsers);
2474
2475 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002476
2477 // Current user has switched, evict all current clients.
2478 std::vector<sp<BasicClient>> evicted;
2479 for (auto& i : mActiveClientManager.getAll()) {
2480 auto clientSp = i->getValue();
2481
2482 if (clientSp.get() == nullptr) {
2483 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2484 continue;
2485 }
2486
Ruben Brunk6267b532015-04-30 17:44:07 -07002487 // Don't evict clients that are still allowed.
2488 uid_t clientUid = clientSp->getClientUid();
2489 userid_t clientUserId = multiuser_get_user_id(clientUid);
2490 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2491 continue;
2492 }
2493
Ruben Brunk36597b22015-03-20 22:15:57 -07002494 evicted.push_back(clientSp);
2495
2496 String8 curTime = getFormattedCurrentTime();
2497
2498 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2499 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002500
Ruben Brunk36597b22015-03-20 22:15:57 -07002501 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002502 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002503 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2504 " to user switch.", i->getKey().string(),
2505 String8{clientSp->getPackageName()}.string(),
2506 i->getOwnerId(), i->getPriority().getScore(),
2507 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002508
2509 }
2510
2511 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2512 // blocking other clients from connecting in mServiceLockWrapper if held.
2513 mServiceLock.unlock();
2514
2515 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002516 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002517
2518 for (auto& i : evicted) {
2519 i->disconnect();
2520 }
2521
Jayant Chowdhary12361932018-08-27 14:46:13 -07002522 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002523
2524 // Reacquire mServiceLock
2525 mServiceLock.lock();
2526}
Ruben Brunkcc776712015-02-17 20:18:47 -08002527
Ruben Brunka8ca9152015-04-07 14:23:40 -07002528void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002529 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002530 Mutex::Autolock l(mLogLock);
2531 mEventLog.add(String8::format("%s : %s", curTime.string(), event));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532}
2533
Ruben Brunka8ca9152015-04-07 14:23:40 -07002534void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002535 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002536 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002537 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002538 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002539}
2540
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002541void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2542 const char* clientPackage) {
2543 // Log the clients evicted
2544 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2545 cameraId, clientPackage, clientPid));
2546}
2547
Ruben Brunka8ca9152015-04-07 14:23:40 -07002548void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002549 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002550 // Log the clients evicted
2551 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002552 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002553}
2554
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002555void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2556 const char* clientPackage) {
2557 // Log the clients evicted
2558 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2559 clientPackage, clientPid));
2560}
2561
Ruben Brunka8ca9152015-04-07 14:23:40 -07002562void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002563 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002564 // Log the client rejected
2565 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002566 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002567}
2568
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002569void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2570 // Log torch event
2571 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2572 torchState, clientPid));
2573}
2574
Ruben Brunk6267b532015-04-30 17:44:07 -07002575void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2576 const std::set<userid_t>& newUserIds) {
2577 String8 newUsers = toString(newUserIds);
2578 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002579 if (oldUsers.size() == 0) {
2580 oldUsers = "<None>";
2581 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002582 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002583 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002584 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002585}
2586
2587void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2588 // Log the device removal
2589 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2590}
2591
2592void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2593 // Log the device removal
2594 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2595}
2596
2597void CameraService::logClientDied(int clientPid, const char* reason) {
2598 // Log the device removal
2599 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002600}
2601
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002602void CameraService::logServiceError(const char* msg, int errorCode) {
2603 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002604 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002605}
2606
Ruben Brunk36597b22015-03-20 22:15:57 -07002607status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2608 uint32_t flags) {
2609
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 // Permission checks
2611 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002612 case SHELL_COMMAND_TRANSACTION: {
2613 int in = data.readFileDescriptor();
2614 int out = data.readFileDescriptor();
2615 int err = data.readFileDescriptor();
2616 int argc = data.readInt32();
2617 Vector<String16> args;
2618 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2619 args.add(data.readString16());
2620 }
2621 sp<IBinder> unusedCallback;
2622 sp<IResultReceiver> resultReceiver;
2623 status_t status;
2624 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2625 return status;
2626 }
2627 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2628 return status;
2629 }
2630 status = shellCommand(in, out, err, args);
2631 if (resultReceiver != nullptr) {
2632 resultReceiver->send(status);
2633 }
2634 return NO_ERROR;
2635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 }
2637
2638 return BnCameraService::onTransact(code, data, reply, flags);
2639}
2640
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641// We share the media players for shutter and recording sound for all clients.
2642// A reference count is kept to determine when we will actually release the
2643// media players.
2644
Jaekyun Seokef498052018-03-23 13:09:44 +09002645sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2646 sp<MediaPlayer> mp = new MediaPlayer();
2647 status_t error;
2648 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002649 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002650 error = mp->prepare();
2651 }
2652 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002653 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002654 mp->disconnect();
2655 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002656 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 }
2658 return mp;
2659}
2660
username5755fea2018-12-27 09:48:08 +08002661void CameraService::increaseSoundRef() {
2662 Mutex::Autolock lock(mSoundLock);
2663 mSoundRef++;
2664}
2665
2666void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002667 ATRACE_CALL();
2668
username5755fea2018-12-27 09:48:08 +08002669 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2670 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2671 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2672 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2673 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2674 }
2675 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2676 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2677 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2678 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002679 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002680 }
2681 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2682 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2683 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2684 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2685 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002686 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687}
2688
username5755fea2018-12-27 09:48:08 +08002689void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002691 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 if (--mSoundRef) return;
2693
2694 for (int i = 0; i < NUM_SOUNDS; i++) {
2695 if (mSoundPlayer[i] != 0) {
2696 mSoundPlayer[i]->disconnect();
2697 mSoundPlayer[i].clear();
2698 }
2699 }
2700}
2701
2702void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002703 ATRACE_CALL();
2704
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 LOG1("playSound(%d)", kind);
2706 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002707 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 sp<MediaPlayer> player = mSoundPlayer[kind];
2709 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002710 player->seekTo(0);
2711 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 }
2713}
2714
2715// ----------------------------------------------------------------------------
2716
2717CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002718 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002719 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002720 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002721 const String8& cameraIdStr,
2722 int api1CameraId, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002723 int clientPid, uid_t clientUid,
2724 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002725 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08002726 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002727 clientPackageName, clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002728 cameraIdStr, cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002729 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002730 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002731 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08002732{
Jayant Chowdhary12361932018-08-27 14:46:13 -07002733 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002734 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735
Igor Murashkin44cfcf02013-03-01 16:22:28 -08002736 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737
username5755fea2018-12-27 09:48:08 +08002738 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002739
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002740 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741}
2742
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743// tear down the client
2744CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002745 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08002746 mDestructionStarted = true;
2747
username5755fea2018-12-27 09:48:08 +08002748 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07002749 // unconditionally disconnect. function is idempotent
2750 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751}
2752
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002753sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2754
Igor Murashkin634a5152013-02-20 17:15:11 -08002755CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002756 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002757 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002758 const String8& cameraIdStr, int cameraFacing,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002759 int clientPid, uid_t clientUid,
2760 int servicePid):
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002761 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002762 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002763 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002764 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07002765 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002766 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002767 mRemoteBinder(remoteCallback)
Igor Murashkin634a5152013-02-20 17:15:11 -08002768{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002769 if (sCameraService == nullptr) {
2770 sCameraService = cameraService;
2771 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002772 mOpsActive = false;
Igor Murashkin634a5152013-02-20 17:15:11 -08002773 mDestructionStarted = false;
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08002774
2775 // In some cases the calling code has no access to the package it runs under.
2776 // For example, NDK camera API.
2777 // In this case we will get the packages for the calling UID and pick the first one
2778 // for attributing the app op. This will work correctly for runtime permissions
2779 // as for legacy apps we will toggle the app op for all packages in the UID.
2780 // The caveat is that the operation may be attributed to the wrong package and
2781 // stats based on app ops may be slightly off.
2782 if (mClientPackageName.size() <= 0) {
2783 sp<IServiceManager> sm = defaultServiceManager();
2784 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2785 if (binder == 0) {
2786 ALOGE("Cannot get permission service");
2787 // Leave mClientPackageName unchanged (empty) and the further interaction
2788 // with camera will fail in BasicClient::startCameraOps
2789 return;
2790 }
2791
2792 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2793 Vector<String16> packages;
2794
2795 permCtrl->getPackagesForUid(mClientUid, packages);
2796
2797 if (packages.isEmpty()) {
2798 ALOGE("No packages for calling UID");
2799 // Leave mClientPackageName unchanged (empty) and the further interaction
2800 // with camera will fail in BasicClient::startCameraOps
2801 return;
2802 }
2803 mClientPackageName = packages[0];
2804 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08002805 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002806 mAppOpsManager = std::make_unique<AppOpsManager>();
2807 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07002808
2809 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08002810}
2811
2812CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07002813 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08002814 mDestructionStarted = true;
2815}
2816
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002817binder::Status CameraService::BasicClient::disconnect() {
2818 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002819 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002820 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07002821 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002822 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08002823
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002824 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002825 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07002826 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2827 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002828
2829 sp<IBinder> remote = getRemote();
2830 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002831 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08002832 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002833
2834 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07002835 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002836 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2837 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2838 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002839
Igor Murashkincba2c162013-03-20 15:56:31 -07002840 // client shouldn't be able to call into us anymore
2841 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002842
2843 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08002844}
2845
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002846status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2847 // No dumping of clients directly over Binder,
2848 // must go through CameraService::dump
2849 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002850 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08002851 return OK;
2852}
2853
Ruben Brunkcc776712015-02-17 20:18:47 -08002854String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002855 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08002856}
2857
2858
2859int CameraService::BasicClient::getClientPid() const {
2860 return mClientPid;
2861}
2862
Ruben Brunk6267b532015-04-30 17:44:07 -07002863uid_t CameraService::BasicClient::getClientUid() const {
2864 return mClientUid;
2865}
2866
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002867bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2868 // Defaults to API2.
2869 return level == API_2;
2870}
2871
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002872status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002873 {
2874 Mutex::Autolock l(mAudioRestrictionLock);
2875 mAudioRestriction = mode;
2876 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07002877 sCameraService->updateAudioRestriction();
2878 return OK;
2879}
2880
2881int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002882 return sCameraService->updateAudioRestriction();
2883}
2884
2885int32_t CameraService::BasicClient::getAudioRestriction() const {
2886 Mutex::Autolock l(mAudioRestrictionLock);
2887 return mAudioRestriction;
2888}
2889
2890bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
2891 switch (mode) {
2892 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
2893 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
2894 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
2895 return true;
2896 default:
2897 return false;
2898 }
2899}
2900
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002901status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002902 ATRACE_CALL();
2903
Igor Murashkine6800ce2013-03-04 17:25:57 -08002904 {
2905 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002906 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08002907 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002908 if (mAppOpsManager != nullptr) {
2909 // Notify app ops that the camera is not available
2910 mOpsCallback = new OpsCallback(this);
2911 int32_t res;
2912 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2913 mClientPackageName, mOpsCallback);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002914 res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
2915 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
2916 String16("start camera ") + String16(mCameraIdStr));
Igor Murashkine6800ce2013-03-04 17:25:57 -08002917
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002918 if (res == AppOpsManager::MODE_ERRORED) {
2919 ALOGI("Camera %s: Access for \"%s\" has been revoked",
2920 mCameraIdStr.string(), String8(mClientPackageName).string());
2921 return PERMISSION_DENIED;
2922 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002923
Shuzhen Wang2c656792020-04-13 17:36:49 -07002924 // If the calling Uid is trusted (a native service), the AppOpsManager could
2925 // return MODE_IGNORED. Do not treat such case as error.
2926 if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002927 ALOGI("Camera %s: Access for \"%s\" has been restricted",
2928 mCameraIdStr.string(), String8(mClientPackageName).string());
2929 // Return the same error as for device policy manager rejection
2930 return -EACCES;
2931 }
Svetoslav28e8ef72015-05-11 19:21:31 -07002932 }
2933
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002934 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002935
2936 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002937 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002938
Emilian Peev573291c2018-02-10 02:10:56 +00002939 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2940 if (canCastToApiClient(API_2)) {
2941 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2942 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002943 // Transition device state to OPEN
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002944 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
Emilian Peev573291c2018-02-10 02:10:56 +00002945 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002946
Emilian Peev53722fa2019-02-22 17:47:20 -08002947 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2948
Shuzhen Wang695044d2020-03-06 09:02:23 -08002949 // Notify listeners of camera open/close status
2950 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2951
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002952 return OK;
2953}
2954
2955status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002956 ATRACE_CALL();
2957
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002958 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002959 if (mOpsActive) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002960 // Notify app ops that the camera is available again
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002961 if (mAppOpsManager != nullptr) {
2962 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08002963 mClientPackageName, mClientFeatureId);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002964 mOpsActive = false;
2965 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002966 // This function is called when a client disconnects. This should
2967 // release the camera, but actually only if it was in a proper
2968 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002969 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01002970 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002971
Ruben Brunkcc776712015-02-17 20:18:47 -08002972 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002973 sCameraService->updateStatus(StatusInternal::PRESENT,
2974 mCameraIdStr, rejected);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002975
Emilian Peev573291c2018-02-10 02:10:56 +00002976 int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2977 if (canCastToApiClient(API_2)) {
2978 apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2979 }
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07002980 // Transition device state to CLOSED
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002981 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
Emilian Peev573291c2018-02-10 02:10:56 +00002982 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002983 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07002984 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002985 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2986 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08002987 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002988 mOpsCallback.clear();
2989
Emilian Peev53722fa2019-02-22 17:47:20 -08002990 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2991
Shuzhen Wang695044d2020-03-06 09:02:23 -08002992 // Notify listeners of camera open/close status
2993 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2994
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08002995 return OK;
2996}
2997
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07002998void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002999 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003000 if (mAppOpsManager == nullptr) {
3001 return;
3002 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003003 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003004 if (op != AppOpsManager::OP_CAMERA) {
3005 ALOGW("Unexpected app ops notification received: %d", op);
3006 return;
3007 }
3008
3009 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003010 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003011 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003012 ALOGV("checkOp returns: %d, %s ", res,
3013 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3014 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3015 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3016 "UNKNOWN");
3017
3018 if (res != AppOpsManager::MODE_ALLOWED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003019 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003020 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003021 block();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003022 }
3023}
3024
Svet Ganova453d0d2018-01-11 15:37:58 -08003025void CameraService::BasicClient::block() {
3026 ATRACE_CALL();
3027
3028 // Reset the client PID to allow server-initiated disconnect,
3029 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003030 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003031 CaptureResultExtras resultExtras; // a dummy result (invalid)
3032 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3033 disconnect();
3034}
3035
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036// ----------------------------------------------------------------------------
3037
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003038void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003039 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003040 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003041 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003042 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3043 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3044 api1ErrorCode = CAMERA_ERROR_DISABLED;
3045 }
3046 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003047 } else {
3048 ALOGE("mRemoteCallback is NULL!!");
3049 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003050}
3051
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003052// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003053binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003054 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003055 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003056}
3057
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003058bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3059 return level == API_1;
3060}
3061
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003062CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3063 mClient(client) {
3064}
3065
3066void CameraService::Client::OpsCallback::opChanged(int32_t op,
3067 const String16& packageName) {
3068 sp<BasicClient> client = mClient.promote();
3069 if (client != NULL) {
3070 client->opChanged(op, packageName);
3071 }
3072}
3073
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003075// UidPolicy
3076// ----------------------------------------------------------------------------
3077
3078void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003079 Mutex::Autolock _l(mUidLock);
3080
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003081 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003082 status_t res = mAm.linkToDeath(this);
3083 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003084 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003085 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003086 ActivityManager::PROCESS_STATE_UNKNOWN,
3087 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003088 if (res == OK) {
3089 mRegistered = true;
3090 ALOGV("UidPolicy: Registered with ActivityManager");
3091 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003092}
3093
3094void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003095 Mutex::Autolock _l(mUidLock);
3096
Steven Moreland2f348142019-07-02 15:59:07 -07003097 mAm.unregisterUidObserver(this);
3098 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003099 mRegistered = false;
3100 mActiveUids.clear();
3101 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003102}
3103
3104void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3105 onUidIdle(uid, disabled);
3106}
3107
3108void CameraService::UidPolicy::onUidActive(uid_t uid) {
3109 Mutex::Autolock _l(mUidLock);
3110 mActiveUids.insert(uid);
3111}
3112
3113void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3114 bool deleted = false;
3115 {
3116 Mutex::Autolock _l(mUidLock);
3117 if (mActiveUids.erase(uid) > 0) {
3118 deleted = true;
3119 }
3120 }
3121 if (deleted) {
3122 sp<CameraService> service = mService.promote();
3123 if (service != nullptr) {
3124 service->blockClientsForUid(uid);
3125 }
3126 }
3127}
3128
Emilian Peev53722fa2019-02-22 17:47:20 -08003129void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003130 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003131 bool procStateChange = false;
3132 {
3133 Mutex::Autolock _l(mUidLock);
3134 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3135 (mMonitoredUids[uid].first != procState)) {
3136 mMonitoredUids[uid].first = procState;
3137 procStateChange = true;
3138 }
3139 }
3140
3141 if (procStateChange) {
3142 sp<CameraService> service = mService.promote();
3143 if (service != nullptr) {
3144 service->notifyMonitoredUids();
3145 }
3146 }
3147}
3148
3149void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3150 Mutex::Autolock _l(mUidLock);
3151 auto it = mMonitoredUids.find(uid);
3152 if (it != mMonitoredUids.end()) {
3153 it->second.second++;
3154 } else {
3155 mMonitoredUids.emplace(
3156 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3157 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3158 }
3159}
3160
3161void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3162 Mutex::Autolock _l(mUidLock);
3163 auto it = mMonitoredUids.find(uid);
3164 if (it != mMonitoredUids.end()) {
3165 it->second.second--;
3166 if (it->second.second == 0) {
3167 mMonitoredUids.erase(it);
3168 }
3169 } else {
3170 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3171 }
3172}
3173
Svet Ganov7b4ab782018-03-25 12:48:10 -07003174bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003175 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003176 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003177}
3178
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003179static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3180static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003181
Svet Ganov7b4ab782018-03-25 12:48:10 -07003182bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003183 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003184 // If activity manager is unreachable, assume everything is active
3185 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003186 return true;
3187 }
3188 auto it = mOverrideUids.find(uid);
3189 if (it != mOverrideUids.end()) {
3190 return it->second;
3191 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003192 bool active = mActiveUids.find(uid) != mActiveUids.end();
3193 if (!active) {
3194 // We want active UIDs to always access camera with their first attempt since
3195 // there is no guarantee the app is robustly written and would retry getting
3196 // the camera on failure. The inverse case is not a problem as we would take
3197 // camera away soon once we get the callback that the uid is no longer active.
3198 ActivityManager am;
3199 // Okay to access with a lock held as UID changes are dispatched without
3200 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003201 int64_t startTimeMillis = 0;
3202 do {
3203 // TODO: Fix this b/109950150!
3204 // Okay this is a hack. There is a race between the UID turning active and
3205 // activity being resumed. The proper fix is very risky, so we temporary add
3206 // some polling which should happen pretty rarely anyway as the race is hard
3207 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003208 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003209 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003210 if (active) {
3211 break;
3212 }
3213 if (startTimeMillis <= 0) {
3214 startTimeMillis = uptimeMillis();
3215 }
3216 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003217 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003218 if (remainingTimeMillis <= 0) {
3219 break;
3220 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003221 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3222
3223 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003224 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003225 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003226 } while (true);
3227
Svet Ganov7b4ab782018-03-25 12:48:10 -07003228 if (active) {
3229 // Now that we found out the UID is actually active, cache that
3230 mActiveUids.insert(uid);
3231 }
3232 }
3233 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003234}
3235
Varun Shahb42f1eb2019-04-16 14:45:13 -07003236int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3237 Mutex::Autolock _l(mUidLock);
3238 return getProcStateLocked(uid);
3239}
3240
3241int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3242 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3243 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3244 procState = mMonitoredUids[uid].first;
3245 }
3246 return procState;
3247}
3248
Svet Ganov7b4ab782018-03-25 12:48:10 -07003249void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3250 String16 callingPackage, bool active) {
3251 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003252}
3253
Svet Ganov7b4ab782018-03-25 12:48:10 -07003254void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3255 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003256}
3257
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003258void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3259 Mutex::Autolock _l(mUidLock);
3260 ALOGV("UidPolicy: ActivityManager has died");
3261 mRegistered = false;
3262 mActiveUids.clear();
3263}
3264
Svet Ganov7b4ab782018-03-25 12:48:10 -07003265void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3266 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003267 bool wasActive = false;
3268 bool isActive = false;
3269 {
3270 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003271 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003272 mOverrideUids.erase(uid);
3273 if (insert) {
3274 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3275 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003276 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003277 }
3278 if (wasActive != isActive && !isActive) {
3279 sp<CameraService> service = mService.promote();
3280 if (service != nullptr) {
3281 service->blockClientsForUid(uid);
3282 }
3283 }
3284}
3285
3286// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003287// SensorPrivacyPolicy
3288// ----------------------------------------------------------------------------
3289void CameraService::SensorPrivacyPolicy::registerSelf() {
3290 Mutex::Autolock _l(mSensorPrivacyLock);
3291 if (mRegistered) {
3292 return;
3293 }
Steven Moreland3cf67172020-01-29 11:44:22 -08003294 mSpm.addSensorPrivacyListener(this);
3295 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3296 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003297 if (res == OK) {
3298 mRegistered = true;
3299 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3300 }
3301}
3302
3303void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3304 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003305 mSpm.removeSensorPrivacyListener(this);
3306 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003307 mRegistered = false;
3308 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3309}
3310
3311bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3312 Mutex::Autolock _l(mSensorPrivacyLock);
3313 return mSensorPrivacyEnabled;
3314}
3315
3316binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3317 {
3318 Mutex::Autolock _l(mSensorPrivacyLock);
3319 mSensorPrivacyEnabled = enabled;
3320 }
3321 // if sensor privacy is enabled then block all clients from accessing the camera
3322 if (enabled) {
3323 sp<CameraService> service = mService.promote();
3324 if (service != nullptr) {
3325 service->blockAllClients();
3326 }
3327 }
3328 return binder::Status::ok();
3329}
3330
3331void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3332 Mutex::Autolock _l(mSensorPrivacyLock);
3333 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3334 mRegistered = false;
3335}
3336
3337// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003338// CameraState
3339// ----------------------------------------------------------------------------
3340
3341CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003342 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3343 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3344 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003345
3346CameraService::CameraState::~CameraState() {}
3347
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003348CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003349 Mutex::Autolock lock(mStatusLock);
3350 return mStatus;
3351}
3352
Shuzhen Wang43858162020-01-10 13:42:15 -08003353std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3354 Mutex::Autolock lock(mStatusLock);
3355 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3356 return res;
3357}
3358
Ruben Brunkcc776712015-02-17 20:18:47 -08003359CameraParameters CameraService::CameraState::getShimParams() const {
3360 return mShimParams;
3361}
3362
3363void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3364 mShimParams = params;
3365}
3366
3367int CameraService::CameraState::getCost() const {
3368 return mCost;
3369}
3370
3371std::set<String8> CameraService::CameraState::getConflicting() const {
3372 return mConflicting;
3373}
3374
3375String8 CameraService::CameraState::getId() const {
3376 return mId;
3377}
3378
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003379SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3380 return mSystemCameraKind;
3381}
3382
Shuzhen Wang43858162020-01-10 13:42:15 -08003383bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3384 Mutex::Autolock lock(mStatusLock);
3385 auto result = mUnavailablePhysicalIds.insert(physicalId);
3386 return result.second;
3387}
3388
3389bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3390 Mutex::Autolock lock(mStatusLock);
3391 auto count = mUnavailablePhysicalIds.erase(physicalId);
3392 return count > 0;
3393}
3394
Ruben Brunkcc776712015-02-17 20:18:47 -08003395// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003396// ClientEventListener
3397// ----------------------------------------------------------------------------
3398
3399void CameraService::ClientEventListener::onClientAdded(
3400 const resource_policy::ClientDescriptor<String8,
3401 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003402 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003403 if (basicClient.get() != nullptr) {
3404 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3405 notifier.noteStartCamera(descriptor.getKey(),
3406 static_cast<int>(basicClient->getClientUid()));
3407 }
3408}
3409
3410void CameraService::ClientEventListener::onClientRemoved(
3411 const resource_policy::ClientDescriptor<String8,
3412 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003413 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003414 if (basicClient.get() != nullptr) {
3415 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3416 notifier.noteStopCamera(descriptor.getKey(),
3417 static_cast<int>(basicClient->getClientUid()));
3418 }
3419}
3420
3421
3422// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003423// CameraClientManager
3424// ----------------------------------------------------------------------------
3425
Ruben Brunk99e69712015-05-26 17:25:07 -07003426CameraService::CameraClientManager::CameraClientManager() {
3427 setListener(std::make_shared<ClientEventListener>());
3428}
3429
Ruben Brunkcc776712015-02-17 20:18:47 -08003430CameraService::CameraClientManager::~CameraClientManager() {}
3431
3432sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3433 const String8& id) const {
3434 auto descriptor = get(id);
3435 if (descriptor == nullptr) {
3436 return sp<BasicClient>{nullptr};
3437 }
3438 return descriptor->getValue();
3439}
3440
3441String8 CameraService::CameraClientManager::toString() const {
3442 auto all = getAll();
3443 String8 ret("[");
3444 bool hasAny = false;
3445 for (auto& i : all) {
3446 hasAny = true;
3447 String8 key = i->getKey();
3448 int32_t cost = i->getCost();
3449 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003450 int32_t score = i->getPriority().getScore();
3451 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003452 auto conflicting = i->getConflicting();
3453 auto clientSp = i->getValue();
3454 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003455 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003456 if (clientSp.get() != nullptr) {
3457 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003458 uid_t clientUid = clientSp->getClientUid();
3459 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003460 }
Emilian Peev8131a262017-02-01 12:33:43 +00003461 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3462 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003463
Ruben Brunk6267b532015-04-30 17:44:07 -07003464 if (clientSp.get() != nullptr) {
3465 ret.appendFormat("User Id: %d, ", clientUserId);
3466 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003467 if (packageName.size() != 0) {
3468 ret.appendFormat("Client Package Name: %s", packageName.string());
3469 }
3470
3471 ret.append(", Conflicting Client Devices: {");
3472 for (auto& j : conflicting) {
3473 ret.appendFormat("%s, ", j.string());
3474 }
3475 ret.append("})");
3476 }
3477 if (hasAny) ret.append("\n");
3478 ret.append("]\n");
3479 return ret;
3480}
3481
3482CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3483 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003484 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3485 int32_t state) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003486
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003487 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003488 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3489 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3490
Ruben Brunkcc776712015-02-17 20:18:47 -08003491 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003492 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08003493}
3494
3495CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3496 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3497 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003498 partial->getConflicting(), partial->getPriority().getScore(),
3499 partial->getOwnerId(), partial->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08003500}
3501
3502// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503
3504static const int kDumpLockRetries = 50;
3505static const int kDumpLockSleep = 60000;
3506
3507static bool tryLock(Mutex& mutex)
3508{
3509 bool locked = false;
3510 for (int i = 0; i < kDumpLockRetries; ++i) {
3511 if (mutex.tryLock() == NO_ERROR) {
3512 locked = true;
3513 break;
3514 }
3515 usleep(kDumpLockSleep);
3516 }
3517 return locked;
3518}
3519
3520status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003521 ATRACE_CALL();
3522
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003523 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003524 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003525 CameraThreadState::getCallingPid(),
3526 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003527 return NO_ERROR;
3528 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003529 bool locked = tryLock(mServiceLock);
3530 // failed to lock - CameraService is probably deadlocked
3531 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003532 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003533 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003534
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003535 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003536 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07003537
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003538 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003539 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08003540
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003541 if (locked) mServiceLock.unlock();
3542 return NO_ERROR;
3543 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003544 dprintf(fd, "\n== Service global info: ==\n\n");
3545 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003546 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07003547 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
3548 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003549 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3550 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3551 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003552 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003553 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3554 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003555
3556 dumpEventLog(fd);
3557
3558 bool stateLocked = tryLock(mCameraStatesLock);
3559 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003560 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003561 }
3562
Emilian Peevbd8c5032018-02-14 23:05:40 +00003563 int argSize = args.size();
3564 for (int i = 0; i < argSize; i++) {
3565 if (args[i] == TagMonitor::kMonitorOption) {
3566 if (i + 1 < argSize) {
3567 mMonitorTags = String8(args[i + 1]);
3568 }
3569 break;
3570 }
3571 }
3572
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003573 for (auto& state : mCameraStates) {
3574 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003575
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003576 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003577
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003578 CameraParameters p = state.second->getShimParams();
3579 if (!p.isEmpty()) {
3580 dprintf(fd, " Camera1 API shim is using parameters:\n ");
3581 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003582 }
3583
3584 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08003585 if (clientDescriptor != nullptr) {
3586 dprintf(fd, " Device %s is open. Client instance dump:\n",
3587 cameraId.string());
3588 dprintf(fd, " Client priority score: %d state: %d\n",
3589 clientDescriptor->getPriority().getScore(),
3590 clientDescriptor->getPriority().getState());
3591 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
3592
3593 auto client = clientDescriptor->getValue();
3594 dprintf(fd, " Client package: %s\n",
3595 String8(client->getPackageName()).string());
3596
3597 client->dumpClient(fd, args);
3598 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003599 dprintf(fd, " Device %s is closed, no client instance\n",
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003600 cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003601 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003602
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003603 }
3604
3605 if (stateLocked) mCameraStatesLock.unlock();
3606
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003607 if (locked) mServiceLock.unlock();
3608
Emilian Peevf53f66e2017-04-11 14:29:43 +01003609 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003610
3611 dprintf(fd, "\n== Vendor tags: ==\n\n");
3612
3613 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3614 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00003615 sp<VendorTagDescriptorCache> cache =
3616 VendorTagDescriptorCache::getGlobalVendorTagCache();
3617 if (cache == NULL) {
3618 dprintf(fd, "No vendor tags.\n");
3619 } else {
3620 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3621 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003622 } else {
3623 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3624 }
3625
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003626 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003627 dprintf(fd, "\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003628 camera3::CameraTraces::dump(fd, args);
3629
3630 // Process dump arguments, if any
3631 int n = args.size();
3632 String16 verboseOption("-v");
3633 String16 unreachableOption("--unreachable");
3634 for (int i = 0; i < n; i++) {
3635 if (args[i] == verboseOption) {
3636 // change logging level
3637 if (i + 1 >= n) continue;
3638 String8 levelStr(args[i+1]);
3639 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003640 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003641 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003642 } else if (args[i] == unreachableOption) {
3643 // Dump memory analysis
3644 // TODO - should limit be an argument parameter?
3645 UnreachableMemoryInfo info;
3646 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3647 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003648 dprintf(fd, "\n== Unable to dump unreachable memory. "
3649 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003650 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003651 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08003652 std::string s = info.ToString(/*log_contents*/ true);
3653 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654 }
3655 }
3656 }
3657 return NO_ERROR;
3658}
3659
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003660void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003661 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003662
3663 Mutex::Autolock l(mLogLock);
3664 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003665 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003666 }
3667
3668 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003669 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003670 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003671 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003672 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003673 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003674}
3675
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003676void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003677 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003678 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3679 if (mTorchClientMap[i] == who) {
3680 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003681 String8 cameraId = mTorchClientMap.keyAt(i);
3682 status_t res = mFlashlight->setTorchMode(cameraId, false);
3683 if (res) {
3684 ALOGE("%s: torch client died but couldn't turn off torch: "
3685 "%s (%d)", __FUNCTION__, strerror(-res), res);
3686 return;
3687 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003688 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003689 break;
3690 }
3691 }
3692}
3693
Ruben Brunkcc776712015-02-17 20:18:47 -08003694/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003695
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003696 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07003697 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3698 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07003699 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003700 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003701 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003702
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003703 // check torch client
3704 handleTorchClientBinderDied(who);
3705
3706 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08003707 if(!evictClientIdByRemote(who)) {
3708 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003709 return;
3710 }
3711
Ruben Brunkcc776712015-02-17 20:18:47 -08003712 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3713 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07003714}
3715
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003716void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003717 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08003718}
3719
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003720void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3721 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003722 // Do not lock mServiceLock here or can get into a deadlock from
3723 // connect() -> disconnect -> updateStatus
3724
3725 auto state = getCameraState(cameraId);
3726
3727 if (state == nullptr) {
3728 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3729 cameraId.string());
3730 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07003731 }
3732
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003733 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
3734 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3735 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3736 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
3737 return;
3738 }
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003739 bool supportsHAL3 = false;
3740 // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3741 // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3742 // mInterfaceMutex together, which can lead to deadlocks)
3743 binder::Status sRet =
3744 supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3745 &supportsHAL3);
3746 if (!sRet.isOk()) {
3747 ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3748 __FUNCTION__, cameraId.string());
3749 return;
3750 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003751 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08003752 // of the listeners with both the mStatusLock and mStatusListenerLock held
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003753 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind, &supportsHAL3]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003754 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003755
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003756 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003757 // Update torch status if it has a flash unit.
3758 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003759 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003760 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3761 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003762 TorchModeStatus newTorchStatus =
3763 status == StatusInternal::PRESENT ?
3764 TorchModeStatus::AVAILABLE_OFF :
3765 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07003766 if (torchStatus != newTorchStatus) {
3767 onTorchStatusChangedLocked(cameraId, newTorchStatus);
3768 }
3769 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003770 }
3771
3772 Mutex::Autolock lock(mStatusListenerLock);
3773
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003774 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08003775
Ruben Brunkcc776712015-02-17 20:18:47 -08003776 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003777 bool isVendorListener = listener->isVendorListener();
3778 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
3779 listener->getListenerPid(), listener->getListenerUid()) ||
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003780 (isVendorListener && !supportsHAL3)) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07003781 ALOGV("Skipping discovery callback for system-only camera/HAL1 device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003782 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003783 continue;
3784 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003785 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08003786 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08003787 }
3788 });
Igor Murashkincba2c162013-03-20 15:56:31 -07003789}
3790
Shuzhen Wang695044d2020-03-06 09:02:23 -08003791void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3792 const String16& clientPackageName) {
3793 Mutex::Autolock lock(mStatusListenerLock);
3794
3795 for (const auto& it : mListenerList) {
3796 if (!it->isOpenCloseCallbackAllowed()) {
3797 continue;
3798 }
3799
3800 binder::Status ret;
3801 String16 cameraId64(cameraId);
3802 if (open) {
3803 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
3804 } else {
3805 ret = it->getListener()->onCameraClosed(cameraId64);
3806 }
3807 if (!ret.isOk()) {
3808 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3809 ret.exceptionCode());
3810 }
3811 }
3812}
3813
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003814template<class Func>
3815void CameraService::CameraState::updateStatus(StatusInternal status,
3816 const String8& cameraId,
3817 std::initializer_list<StatusInternal> rejectSourceStates,
3818 Func onStatusUpdatedLocked) {
3819 Mutex::Autolock lock(mStatusLock);
3820 StatusInternal oldStatus = mStatus;
3821 mStatus = status;
3822
3823 if (oldStatus == status) {
3824 return;
3825 }
3826
3827 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3828 cameraId.string(), oldStatus, status);
3829
3830 if (oldStatus == StatusInternal::NOT_PRESENT &&
3831 (status != StatusInternal::PRESENT &&
3832 status != StatusInternal::ENUMERATING)) {
3833
3834 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3835 __FUNCTION__);
3836 mStatus = oldStatus;
3837 return;
3838 }
3839
3840 /**
3841 * Sometimes we want to conditionally do a transition.
3842 * For example if a client disconnects, we want to go to PRESENT
3843 * only if we weren't already in NOT_PRESENT or ENUMERATING.
3844 */
3845 for (auto& rejectStatus : rejectSourceStates) {
3846 if (oldStatus == rejectStatus) {
3847 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
3848 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3849 mStatus = oldStatus;
3850 return;
3851 }
3852 }
3853
3854 onStatusUpdatedLocked(cameraId, status);
3855}
3856
Eino-Ville Talvalae8c96c72017-06-27 12:24:07 -07003857void CameraService::updateProxyDeviceState(int newState,
Emilian Peev573291c2018-02-10 02:10:56 +00003858 const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003859 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3860 if (proxyBinder == nullptr) return;
3861 String16 id(cameraId);
Emilian Peev573291c2018-02-10 02:10:56 +00003862 proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
Eino-Ville Talvala412fe562015-08-20 17:08:32 -07003863}
3864
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003865status_t CameraService::getTorchStatusLocked(
3866 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003867 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003868 if (!status) {
3869 return BAD_VALUE;
3870 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003871 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3872 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003873 // invalid camera ID or the camera doesn't have a flash unit
3874 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003875 }
3876
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003877 *status = mTorchStatusMap.valueAt(index);
3878 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003879}
3880
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003881status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003882 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003883 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3884 if (index == NAME_NOT_FOUND) {
3885 return BAD_VALUE;
3886 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003887 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003888
3889 return OK;
3890}
3891
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003892void CameraService::notifyPhysicalCameraStatusLocked(int32_t status, const String8& cameraId,
3893 SystemCameraKind deviceKind) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003894 Mutex::Autolock lock(mCameraStatesLock);
3895 for (const auto& state : mCameraStates) {
3896 std::vector<std::string> physicalCameraIds;
3897 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
3898 // This is not a logical multi-camera.
3899 continue;
3900 }
3901 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), cameraId.c_str())
3902 == physicalCameraIds.end()) {
3903 // cameraId is not a physical camera of this logical multi-camera.
3904 continue;
3905 }
3906
3907 String16 id16(state.first), physicalId16(cameraId);
3908 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07003909 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
3910 listener->getListenerPid(), listener->getListenerUid())) {
3911 ALOGV("Skipping discovery callback for system-only camera device %s",
3912 cameraId.c_str());
3913 continue;
3914 }
Shuzhen Wang43858162020-01-10 13:42:15 -08003915 listener->getListener()->onPhysicalCameraStatusChanged(status,
3916 id16, physicalId16);
3917 }
3918 }
3919}
3920
Svet Ganova453d0d2018-01-11 15:37:58 -08003921void CameraService::blockClientsForUid(uid_t uid) {
3922 const auto clients = mActiveClientManager.getAll();
3923 for (auto& current : clients) {
3924 if (current != nullptr) {
3925 const auto basicClient = current->getValue();
3926 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3927 basicClient->block();
3928 }
3929 }
3930 }
3931}
3932
Michael Grooverd1d435a2018-12-18 17:39:42 -08003933void CameraService::blockAllClients() {
3934 const auto clients = mActiveClientManager.getAll();
3935 for (auto& current : clients) {
3936 if (current != nullptr) {
3937 const auto basicClient = current->getValue();
3938 if (basicClient.get() != nullptr) {
3939 basicClient->block();
3940 }
3941 }
3942 }
3943}
3944
Svet Ganova453d0d2018-01-11 15:37:58 -08003945// NOTE: This is a remote API - make sure all args are validated
3946status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3947 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3948 return PERMISSION_DENIED;
3949 }
3950 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3951 return BAD_VALUE;
3952 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003953 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003954 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003955 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003956 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07003957 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003958 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003959 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
3960 return handleSetRotateAndCrop(args);
3961 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
3962 return handleGetRotateAndCrop(out);
Svet Ganova453d0d2018-01-11 15:37:58 -08003963 } else if (args.size() == 1 && args[0] == String16("help")) {
3964 printHelp(out);
3965 return NO_ERROR;
3966 }
3967 printHelp(err);
3968 return BAD_VALUE;
3969}
3970
3971status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003972 String16 packageName = args[1];
3973
Svet Ganova453d0d2018-01-11 15:37:58 -08003974 bool active = false;
3975 if (args[2] == String16("active")) {
3976 active = true;
3977 } else if ((args[2] != String16("idle"))) {
3978 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3979 return BAD_VALUE;
3980 }
Nicholas Sauera3620332019-04-03 14:05:17 -07003981
3982 int userId = 0;
3983 if (args.size() >= 5 && args[3] == String16("--user")) {
3984 userId = atoi(String8(args[4]));
3985 }
3986
3987 uid_t uid;
3988 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3989 return BAD_VALUE;
3990 }
3991
3992 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08003993 return NO_ERROR;
3994}
3995
3996status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07003997 String16 packageName = args[1];
3998
3999 int userId = 0;
4000 if (args.size() >= 4 && args[2] == String16("--user")) {
4001 userId = atoi(String8(args[3]));
4002 }
4003
4004 uid_t uid;
4005 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004006 return BAD_VALUE;
4007 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004008
4009 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004010 return NO_ERROR;
4011}
4012
4013status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004014 String16 packageName = args[1];
4015
4016 int userId = 0;
4017 if (args.size() >= 4 && args[2] == String16("--user")) {
4018 userId = atoi(String8(args[3]));
4019 }
4020
4021 uid_t uid;
4022 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004023 return BAD_VALUE;
4024 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004025
4026 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004027 return dprintf(out, "active\n");
4028 } else {
4029 return dprintf(out, "idle\n");
4030 }
4031}
4032
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004033status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4034 int rotateValue = atoi(String8(args[1]));
4035 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4036 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4037 Mutex::Autolock lock(mServiceLock);
4038
4039 mOverrideRotateAndCropMode = rotateValue;
4040
4041 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4042
4043 const auto clients = mActiveClientManager.getAll();
4044 for (auto& current : clients) {
4045 if (current != nullptr) {
4046 const auto basicClient = current->getValue();
4047 if (basicClient.get() != nullptr) {
4048 basicClient->setRotateAndCropOverride(rotateValue);
4049 }
4050 }
4051 }
4052
4053 return OK;
4054}
4055
4056status_t CameraService::handleGetRotateAndCrop(int out) {
4057 Mutex::Autolock lock(mServiceLock);
4058
4059 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4060}
4061
Svet Ganova453d0d2018-01-11 15:37:58 -08004062status_t CameraService::printHelp(int out) {
4063 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004064 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4065 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4066 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004067 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4068 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4069 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004070 " help print this message\n");
4071}
4072
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004073int32_t CameraService::updateAudioRestriction() {
4074 Mutex::Autolock lock(mServiceLock);
4075 return updateAudioRestrictionLocked();
4076}
4077
4078int32_t CameraService::updateAudioRestrictionLocked() {
4079 int32_t mode = 0;
4080 // iterate through all active client
4081 for (const auto& i : mActiveClientManager.getAll()) {
4082 const auto clientSp = i->getValue();
4083 mode |= clientSp->getAudioRestriction();
4084 }
4085
4086 bool modeChanged = (mAudioRestriction != mode);
4087 mAudioRestriction = mode;
4088 if (modeChanged) {
4089 mAppOps.setCameraAudioRestriction(mode);
4090 }
4091 return mode;
4092}
4093
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094}; // namespace android